Now we'll look at how to create a branch off the main tree.
JSONNode n(JSON_NODE); n.push_back(JSONNode("RootA", "Value in parent node")); JSONNode c(JSON_NODE); c.set_name("ChildNode"); c.push_back(JSONNode("ChildA", "String Value")); c.push_back(JSONNode("ChildB", 42)); n.push_back(c); std::string jc = n.write_formatted(); std::cout << jc << std::endl;
The result will look like this:
{ "RootA" : "Value in parent node", "ChildNode" : { "ChildA" : "String Value", "ChildB" : 42 } }
As in the previous example, we create a root node to hold all of our child nodes on line one using the constructor.
Line 2 adds to the root a string node with the name "RootA" and a value of "Value in parent node".
On line 3 we're creating a new, floating node that will be a branch off the root. It's the same type as our root, JSON_NODE.
set_name lets us name the node that we've just created. If your branch is an object of some kind, you'll likely want to name it properly. Note that if you try to name the root node (n in our case), it won't be written out. The name will only appear if the JSON_NODE is a child of another node.
Lines 5 and 6 add new nodes with values to our branch node c.
Line 7 attaches our branch node c to the root node n after the string node named "RootA".
Line 8 returns the json_string nicely formatted and 9 prints it to stdout.
With these tools, we can create complicated JSON structures and mimick objects with child properties.