4

I'm stuck with jsoncpp. I would like to create an array like this:

"Cords": [{"x": 10, "y": 20}, {"x": 70, "y": 40}, {"x": 15, "y": 65}]

I managed to do the regular stuff with jsoncpp (see below) but I am stuck in this case of making a JSON array.

Json::Value event;

event["name"] = "Joe";
event["Direction"]["left"]["x"] = "1338";
event["Direction"]["right"]["x"] = "1337";

Edit:
I want to print it all within event.
I do not want to print cords separately.

Azeem
  • 11,148
  • 4
  • 27
  • 40
JJ Jones
  • 101
  • 1
  • 7

2 Answers2

5

You need to use the int overload of operator[] to define an array

Json::Value coord(int x, int y)
{
    Json::Value result;
    result["x"] = x;
    result["y"] = y;
    return result;    
}

void make_event(Json::Value & event)
{
    Json::Value & coords = event["Cords"];
    coords[0] = coord(10, 20);
    coords[1] = coord(70, 40);
    coords[2] = coord(15, 65);
}
Caleth
  • 52,200
  • 2
  • 44
  • 75
  • Looks good, @Caleth what would be the best practice if I would have to put this into a function that is void? Right now it says a function-definition is not allowed here before ‘{’ token – JJ Jones Jan 22 '18 at 12:23
  • move the definition of `coord` outside the function that is using it – Caleth Jan 22 '18 at 12:32
  • Works just like intended! Many thanks for your help! – JJ Jones Jan 22 '18 at 12:49
1

May be something like this

Json::Value min;
Json::Value event;
event["x"] = 10;
event["y"] = 20;
min["Cords"] = event;



// Output to see the result

cout<<min.toStyledString()
  • Is it not possible to do it within Json::Value event; somehow? I do not want to print it alone as I am already including other data to event and printing it as a whole. – JJ Jones Jan 22 '18 at 10:53