Euphoria Audio, LLC

Audio, Video and Data Consulting

libJSON Array Example


libJSON is a great C/C++ library written by Jonathan Wallace and can be found on Sourceforge. 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);

The result will look like this:

    "RootA" : "Hello World",
    "ArrayOfNumbers" : [

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.

2 Responses

How does it differ? Looks the same as what's in the 7.0 zip file. What kind of error are you getting when you try to compile? Make sure to add your includes and main function.

  • The above sample code does not compile. This sample differs from the sample in the documentation that comes along with the library.  

  • Leave a Reply