libjson Simple Write Example

This example uses the C interface to create a set of JSON nodes that you can then dump to a string and use however you like.

JSONNODE *n = json_new(JSON_NODE);
json_push_back(n, json_new_a("String Node", "String Value"));
json_push_back(n, json_new_i("Integer Node", 42));
json_push_back(n, json_new_f("Floating Point Node", 3.14));
json_push_back(n, json_new_b("Boolean Node", 1));
json_char *jc = json_write_formatted(n);
printf("%s\n", jc);
json_free(jc);
json_delete(n);

The result will look like this:

{
    "String Node" : "String Value",
    "Integer Node" : 42,
    "Floating Point Node" : 3.14,
    "Boolean Node" : true
}

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, 4 and 5 create and add new integer, floating point and boolean nodes respctively and add them to the root node. Both the integer and floating point methods will create JSON_NUMBER nodes where the numeric values will be printed to a JSON string without any quotation marks. The boolean method will take a 0 or a 1 and print a "true" or "false" in the final JSON string.

Line 6 returns a json_char string that contains nicely formatted JSON code from the structure we just created. The string will be nicely tabbed and returned for human readability. Use this for debugging purposes. If you are going into production, use the json_write method instead which will compact the JSON into a single line that saves space for transmission over the Net or between components.
NOTE: similar to other libraries, the json_write and json_write_formatted methods allocate memory for the string, so you are responsible for freeing the memory after you're finished with it.

Line 8 frees the string that json_write_formatted allocated. Any time you use a library function that returns json_char, make sure to free it!

Line 9 is very important as it will free up all of the memory you've allocated for the JSONNODEs. Always call this function on a node when you're finished with it or you will have some nasty memory leaks to contend with.

That's the simplest way to create a JSON tree.

Chris Larsen 2010-10-08