Creating a JSON array with objects

Jul 31, 2013 at 6:42 AM
Edited Jul 31, 2013 at 7:42 AM
I am trying to creating a JSON array and fill it with objects or fields. Are there any examples to do so?


Much later:

Let me answer my own question:

json::value::element_vector pts;
for( int i=0; i<10; ++i )
{
pts.push_back( make_pair( i, i ) );
}
json::value polygon = json::value::array( pts );
Jul 31, 2013 at 2:58 PM
Does that compile? I'm surprised that the make_pair() call does the right conversion, but C++ can be magical sometimes... :-)

Try this, too:
json::value polygon;

for (int i = 0; i < 10; ++i)
{
    polygon[i] = json::value::number(i);
}
Generally, if you find that there are things not covered by the documentation, the unit tests available in the source code tree are often a good resource to rely on.

Niklas
Aug 1, 2013 at 1:12 AM
Actually I am trying to create the following JSON:

"polygons" : [
{
 "id": "1"
 "poygon": [ [10, 20], [55. 50], [55. 56]. [50,50] ]
},
{
 "id": "2"
 "poygon": [ [12, 22], [55. 52], [55. 56]. [51,52] ]
}
]

Any ideas?
Aug 1, 2013 at 3:03 AM
Edited Aug 1, 2013 at 3:11 AM
OK, I don't have a compiler with me right now, so this may be only approximate, but something like this:
json::value create_point(int x, int y)
{ 
    json::value result; 
    result[0] = x;   // or json::number(x);
    result[1] = y;   // or json::number(y);
    return result; 
}

json::value create_polygons()
{
    json::value first,second;
    first[U("id")] = "1";
    second[U("id")] = "2";

    json::value pol1;
    pol1[0] = create_point(10,20); pol1[1] = create_point(55,50);
    pol1[2] = create_point(55,56); pol1[3] = create_point(50,50);
    json::value pol2;
    pol2[0] = create_point(12,22); pol2[1] = create_point(55,52);
    pol2[2] = create_point(55,56); pol2[3] = create_point(51,52);

   first[U("poygon")] = pol1;
   second[U("poygon")] = pol2;

  json::value result;
  result[0] = first;
  result[1] = second;

  return result;
}
The U() macro is to make the string literals platform-independent: two-byte chars on Windows, single-byte chars on other platforms.
Aug 1, 2013 at 5:40 AM
Thanks! That was most useful. Plus you are right about the unit test, it contains a whole load of good stuff!