digip.org blog

New features of Jansson 2.0, part 2

By Petri Lehtinen on 2011-03-02

This post continues a series of articles that give insight to the new features of Jansson 2.0; see part 1.

This article is about the json_pack() API. It allows the user to build arbitrary JSON values using a simple format string-based approach. As with json_unpack(), the idea has been stolen from Python's C API.

Here are some examples:

json_pack("i", 42);
/* -> JSON integer 42 */

json_pack("{s: s, s: i}", "foo", "bar", "baz", 123);
/* -> JSON object {"foo": "bar", "baz": 123} */

json_pack("{s: [{s: i}, {s: i}]}", "data", "value", 15, "value", 16);
/* -> JSON object {"data": [{"value": 15}, {"value": 16}]} */

The first argument is a format string that describes the type and structure of the value that's being built. The format i creates an integer and s means a string (both as a value and an object key). {} and [] are used to build objects and arrays. Whitespace, : and , are ignored. As the last example shows, objects and arrays can be nested, there is no limit on the nesting depth. json_pack() returns the new JSON value, or NULL on error.

json_pack_ex() is also available. It makes it possible to get error messages and pass flags, although currently no flags are defined. Example:

json_t *value;
json_error_t error;

value = json_pack_ex(&error, 0, "[iii]", 1, 2, 3);
if(!value) {
    fprintf(stderr, "Error: %d:%d: %s\n", error.line, error.column, error.text);
    return -1;  /* error */
}

/* ... */

json_decref(value);

The errors that may occur are problems with the format string (e.g. unbalanced } or an invalid format character), out of memory errors and invalid UTF-8 in strings, so this function is mainly useful for debugging format strings.

json_pack() provides a powerful means of creating JSON values, both simple and complex. Without it, you might need tens of lines of code with ugly temporary variables to make nested objects or arrays. I think this is a great addition to Jansson's API and will make it a whole lot easier to create JSON data in C.

For full details of format characters, see the documentation.

Tags: jansson