0

I know that if I have some integer 'a' and 'b' that I can append them to a Value in Json:

Value root;
Value v = root["int"];
int a = 1;
int b = 2;
v.append(a);
v.append(b);

Resulting Json file:

"int": 
  [
    1,
    2
  ]

But is there also a way to append entire arrays? Perhaps something like this:

Value root;
Value v = root["arrays"];
int a[3] = {1,2,3};
int b[3] = {4,5,6};
v.append(a);
v.append(b);

I'm trying to have my resulting Json file look like:

"arrays": 
  [
    [1, 2, 3],
    [4, 5, 6]
  ]

But instead, Json only appends the pointer address value, which reads as "true":

"arrays": 
  [
    true,
    true
  ]
5
  • you're looking for an .extend() method Commented May 1, 2020 at 18:13
  • whats the result for the second code? Commented May 1, 2020 at 18:23
  • Yeah, an extend() is exactly what I'm looking for, but I can't find one within jsoncpp (github.com/open-source-parsers/jsoncpp). I don't think copy() helps, because I still can't get that array data into the Json file properly. Commented May 1, 2020 at 18:25
  • Rithik: the last box is what I get. Commented May 1, 2020 at 18:29
  • hyde: range-for is close, but it just dumps in all the values of the two arrays without structure, like this: "arrays": [ 1, 2, 3, 4, 5, 6 ] Commented May 1, 2020 at 18:31

1 Answer 1

1

The explicit way is to use range-for with a temp Value.

Value root;
Value v = root["arrays"];
int a[3] = {1,2,3};
int b[3] = {4,5,6};

Value tmp;
for(auto i : a) { tmp.append(i); }
v.append(tmp);

tmp = Value{}; // reset
for(auto i : b) { tmp.append(i); }
v.append(tmp)

A possible helper template function to wrap it nicely:

template<typename RANGE>
Value rangeToValue(RANGE src) {
    Value result;
    for (const auto &value : src) {
        result.append(value);
    }
    return result;
}

Then this should work:

v.append(rangeToValue(a)); v.append(rangeToValue(b));

Sign up to request clarification or add additional context in comments.

1 Comment

Heck yes! You're my favourite person of the day, hyde. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.