This quick example will show you how to add an array to your JSON tree.
JSONNode n(JSON_NODE); n.push_back(JSONNode("RootA", "Hello World")); JSONNode c(JSON_ARRAY); c.set_name("ArrayOfNumbers"); c.push_back(JSONNode("", 16)); c.push_back(JSONNode("", 42)); c.push_back(JSONNode("", 128)); n.push_back(c); std::string jc = n.write_formatted(); std::cout << jc << std::endl;
The result will look like this:
{ "RootA" : "Hello World", "ArrayOfNumbers" : [ 16, 42, 128 ] }
The first line generates a new root node for us to work with. This node will contain the entire JSON structure we want to create. Because this is created on the stack, there is no need to clean it up, it will do that when it goes out of scope.
Line 2 creates a new JSON_STRING node, i.e. a node that will have a string value, and attaches the new node to the end of our original root node n.
Line 3 creates a new child node and this time we're declaring a type of JSON_ARRAY that states the node will contain a number of nameless children nodes. While it's possible to have different data types in the same array, you should keep them all the same and treat it as if it were a typed array. Note that you can have an array of JSON_NODE objects, so you're not limited to simple data types, just be aware that the array will ignore any node names if you have them set.
Lines 5 through 7 add values to the array, in this case they're all integer values. Because a JSON array cannot contain named values, the name parameter is set to "".
Line 8 appends the array to our root node.
9 and 10 retrieve the formatted JSON string and dump it to stdout.