libjson Child Node Example

Now we'll look at how to create a branch off the main tree.

JSONNODE *n = json_new(JSON_NODE);
json_push_back(n, json_new_a("RootA", "Value in parent node"));
JSONNODE *c = json_new(JSON_NODE);
json_set_name(c, "ChildNode");
json_push_back(c, json_new_a("ChildA", "String Value"));
json_push_back(c, json_new_i("ChildB", 42));
json_push_back(n, c);
json_char *jc = json_write_formatted(n);
printf("%s\n", jc);
json_free(jc);
json_delete(n);

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 json_new.

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.

json_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". Note that if you fail to attach the branch to another node, you'll have to delete it manually or risk a memory leak.

Line 8 returns the json_char string nicely formatted and 9 prints it to stdout.

Line 10 frees our JSON string and line 11 loops through our root tree and frees up the memory we've used.

With these tools, we can create complicated JSON structures and mimick objects with child properties.

Chris Larsen 2010-10-08