libjson Array Example

This quick example will show you how to add an array to your JSON tree.

JSONNODE *n = json_new(JSON_NODE);
json_push_back(n, json_new_a("RootA", "Hello World"));
JSONNODE *c = json_new(JSON_ARRAY);
json_set_name(c, "ArrayOfNumbers");
json_push_back(c, json_new_i(NULL, 16));
json_push_back(c, json_new_i(NULL, 42));
json_push_back(c, json_new_i(NULL, 128));
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" : "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. Note that, as mentioned in the documentation, any time you call a json_new… method, you are responsbile for freeing the memory allocated by the method. You can do this manually or by attaching the resulting node pointer to an existing node.

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. The json_new_a method will escape your string values when you go to write the final string.

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 of json_new_i is set to NULL.

Line 8 appends the array to our root node.

9 and 10 retrieve the formatted JSON string and dump it to stdout.

11 frees memory allocated for our JSON string and 12 frees the entire tree structure.

Chris Larsen 2010-10-08