All declarations are in jansson.h, so it’s enough to
#include <jansson.h>
in each source file.
All constants are prefixed with JSON_ (except for those describing the library version, prefixed with JANSSON_). Other identifiers are prefixed with json_. Type names are suffixed with _t and typedef‘d so that the struct keyword need not be used.
The Jansson version is of the form A.B.C, where A is the major version, B is the minor version and C is the micro version. If the micro version is zero, it’s omitted from the version string, i.e. the version string is just A.B.
When a new release only fixes bugs and doesn’t add new features or functionality, the micro version is incremented. When new features are added in a backwards compatible way, the minor version is incremented and the micro version is set to zero. When there are backwards incompatible changes, the major version is incremented and others are set to zero.
The following preprocessor constants specify the current version of the library:
A 3-byte hexadecimal representation of the version, e.g. 0x010201 for version 1.2.1 and 0x010300 for version 1.3. This is useful in numeric comparisions, e.g.:
#if JANSSON_VERSION_HEX >= 0x010300
/* Code specific to version 1.3 and above */
#endif
The JSON specification (RFC 4627) defines the following data types: object, array, string, number, boolean, and null. JSON types are used dynamically; arrays and objects can hold any other data type, including themselves. For this reason, Jansson’s type system is also dynamic in nature. There’s one C type to represent all JSON values, and this structure knows the type of the JSON value it holds.
Objects of :type:`json_t` are always used through a pointer. There are APIs for querying the type, manipulating the reference count, and for constructing and manipulating values of different types.
Unless noted otherwise, all API functions return an error value if an error occurs. Depending on the function’s signature, the error value is either NULL or -1. Invalid arguments or invalid input are apparent sources for errors. Memory allocation and I/O operations may also cause errors.
The type of a JSON value is queried and tested using the following functions:
The reference count is used to track whether a value is still in use or not. When a value is created, it’s reference count is set to 1. If a reference to a value is kept (e.g. a value is stored somewhere for later use), its reference count is incremented, and when the value is no longer needed, the reference count is decremented. When the reference count drops to zero, there are no references left, and the value can be destroyed.
The following functions are used to manipulate the reference count.
Functions creating new JSON values set the reference count to 1. These functions are said to return a new reference. Other functions returning (existing) JSON values do not normally increase the reference count. These functions are said to return a borrowed reference. So, if the user will hold a reference to a value returned as a borrowed reference, he must call json_incref(). As soon as the value is no longer needed, json_decref() should be called to release the reference.
Normally, all functions accepting a JSON value as an argument will manage the reference, i.e. increase and decrease the reference count as needed. However, some functions steal the reference, i.e. they have the same result as if the user called json_decref() on the argument right after calling the function. These functions are suffixed with _new or have _new_ somewhere in their name.
For example, the following code creates a new JSON array and appends an integer to it:
json_t *array, *integer;
array = json_array();
integer = json_integer(42);
json_array_append(array, integer);
json_decref(integer);
Note how the caller has to release the reference to the integer value by calling json_decref(). By using a reference stealing function json_array_append_new() instead of json_array_append(), the code becomes much simpler:
json_t *array = json_array();
json_array_append_new(array, json_integer(42));
In this case, the user doesn’t have to explicitly release the reference to the integer value, as json_array_append_new() steals the reference when appending the value to the array.
In the following sections it is clearly documented whether a function will return a new or borrowed reference or steal a reference to its argument.
A circular reference is created when an object or an array is, directly or indirectly, inserted inside itself. The direct case is simple:
json_t *obj = json_object();
json_object_set(obj, "foo", obj);
Jansson will refuse to do this, and json_object_set() (and all the other such functions for objects and arrays) will return with an error status. The indirect case is the dangerous one:
json_t *arr1 = json_array(), *arr2 = json_array();
json_array_append(arr1, arr2);
json_array_append(arr2, arr1);
In this example, the array arr2 is contained in the array arr1, and vice versa. Jansson cannot check for this kind of indirect circular references without a performance hit, so it’s up to the user to avoid them.
If a circular reference is created, the memory consumed by the values cannot be freed by json_decref(). The reference counts never drops to zero because the values are keeping the references to each other. Moreover, trying to encode the values with any of the encoding functions will fail. The encoder detects circular references and returns an error status.
These three values are implemented as singletons, so the returned pointers won’t change between invocations of these functions.
Returns the JSON true value.
Returns the JSON false value.
Returns JSON false if val is zero, and JSON true otherwise. This is a macro, and equivalent to val ? json_true() : json_false().
New in version 2.4.
Returns the JSON null value.
Jansson uses UTF-8 as the character encoding. All JSON strings must be valid UTF-8 (or ASCII, as it’s a subset of UTF-8). Normal null terminated C strings are used, so JSON strings may not contain embedded null characters. All other Unicode codepoints U+0001 through U+10FFFF are allowed.
Returns a new JSON string, or NULL on error. value must be a valid UTF-8 encoded Unicode string.
Like json_string(), but doesn’t check that value is valid UTF-8. Use this function only if you are certain that this really is the case (e.g. you have already checked it by other means).
Returns the associated value of string as a null terminated UTF-8 encoded string, or NULL if string is not a JSON string.
The retuned value is read-only and must not be modified or freed by the user. It is valid as long as string exists, i.e. as long as its reference count has not dropped to zero.
The JSON specification only contains one numeric type, “number”. The C programming language has distinct types for integer and floating-point numbers, so for practical reasons Jansson also has distinct types for the two. They are called “integer” and “real”, respectively. For more information, see RFC Conformance.
JSON_INTEGER_IS_LONG_LONG
This is a preprocessor variable that holds the value 1 if :type:`json_int_t` is long long, and 0 if it’s long. It can be used as follows:
#if JSON_INTEGER_IS_LONG_LONG /* Code specific for long long */ #else /* Code specific for long */ #endif
JSON_INTEGER_FORMAT
This is a macro that expands to a printf() conversion specifier that corresponds to :type:`json_int_t`, without the leading % sign, i.e. either "lld" or "ld". This macro is required because the actual type of :type:`json_int_t` can be either long or long long, and printf() reuiqres different length modifiers for the two.
Example:
json_int_t x = 123123123; printf("x is %" JSON_INTEGER_FORMAT "\n", x);
Returns a new JSON integer, or NULL on error.
Returns a new JSON real, or NULL on error.
In addition to the functions above, there’s a common query function for integers and reals:
A JSON array is an ordered collection of other JSON values.
Returns a new JSON array, or NULL on error. Initially, the array is empty.
Returns the element in array at position index. The valid range for index is from 0 to the return value of json_array_size() minus 1. If array is not a JSON array, if array is NULL, or if index is out of range, NULL is returned.
A JSON object is a dictionary of key-value pairs, where the key is a Unicode string and the value is any JSON value.
Returns a new JSON object, or NULL on error. Initially, the object is empty.
Get a value corresponding to key from object. Returns NULL if key is not found and on error.
Like json_object_update(), but only the values of existing keys are updated. No new keys are created. Returns 0 on success or -1 on error.
New in version 2.3.
Like json_object_update(), but only new keys are created. The value of any existing key is not changed. Returns 0 on success or -1 on error.
New in version 2.3.
The following macro can be used to iterate through all key-value pairs in an object.
Iterate over every key-value pair of object, running the block of code that follows each time with the proper values set to variables key and value, of types :type:`const char *` and :type:`json_t *` respectively. Example:
/* obj is a JSON object */
const char *key;
json_t *value;
json_object_foreach(obj, key, value) {
/* block of code that uses key and value */
}
The items are not returned in any particular order.
This macro expands to an ordinary for statement upon preprocessing, so its performance is equivalent to that of hand-written iteration code using the object iteration protocol (see below). The main advantage of this macro is that it abstracts away the complexity behind iteration, and makes for shorter, more concise code.
New in version 2.3.
The following functions implement an iteration protocol for objects, allowing to iterate through all key-value pairs in an object. The items are not returned in any particular order, as this would require sorting due to the internal hashtable implementation.
Extract the associated value from iter.
Like json_object_iter_at(), but much faster. Only works for values returned by json_object_iter_key(). Using other keys will lead to segfaults. This function is used internally to implement json_object_foreach().
New in version 2.3.
The iteration protocol can be used for example as follows:
/* obj is a JSON object */
const char *key;
json_t *value;
void *iter = json_object_iter(obj);
while(iter)
{
key = json_object_iter_key(iter);
value = json_object_iter_value(iter);
/* use key and value ... */
iter = json_object_iter_next(obj, iter);
}
Jansson uses a single struct type to pass error information to the user. See sections Decoding, Building Values and Parsing and Validating Values for functions that pass error information using this struct.
The normal use of :type:`json_error_t` is to allocate it on the stack, and pass a pointer to a function. Example:
int main() {
json_t *json;
json_error_t error;
json = json_load_file("/path/to/file.json", 0, &error);
if(!json) {
/* the error variable contains error information */
}
...
}
Also note that if the call succeeded (json != NULL in the above example), the contents of error are generally left unspecified. The decoding functions write to the position member also on success. See Decoding for more info.
All functions also accept NULL as the :type:`json_error_t` pointer, in which case no error information is returned to the caller.
This sections describes the functions that can be used to encode values to JSON. By default, only objects and arrays can be encoded directly, since they are the only valid root values of a JSON text. To encode any JSON value, use the JSON_ENCODE_ANY flag (see below).
By default, the output has no newlines, and spaces are used between array and object elements for a readable output. This behavior can be altered by using the JSON_INDENT and JSON_COMPACT flags described below. A newline is never appended to the end of the encoded JSON data.
Each function takes a flags parameter that controls some aspects of how the data is encoded. Its default value is 0. The following macros can be ORed together to obtain flags.
Specifying this flag makes it possible to encode any JSON value on its own. Without it, only objects and arrays can be passed as the root value to the encoding functions.
Note: Encoding any value may be useful in some scenarios, but it’s generally discouraged as it violates strict compatiblity with RFC 4627. If you use this flag, don’t expect interoperatibility with other JSON systems.
New in version 2.1.
Escape the / characters in strings with \/.
New in version 2.4.
The following functions perform the actual JSON encoding. The result is in UTF-8.
Call callback repeatedly, passing a chunk of the JSON representation of root each time. flags is described above. Returns 0 on success and -1 on error.
New in version 2.2.
This sections describes the functions that can be used to decode JSON text to the Jansson representation of JSON data. The JSON specification requires that a JSON text is either a serialized array or object, and this requirement is also enforced with the following functions. In other words, the top level value in the JSON text being decoded must be either array or object. To decode any JSON value, use the JSON_DECODE_ANY flag (see below).
See RFC Conformance for a discussion on Jansson’s conformance to the JSON specification. It explains many design decisions that affect especially the behavior of the decoder.
Each function takes a flags parameter that can be used to control the behavior of the decoder. Its default value is 0. The following macros can be ORed together to obtain flags.
Issue a decoding error if any JSON object in the input text contains duplicate keys. Without this flag, the value of the last occurence of each key ends up in the result. Key equivalence is checked byte-by-byte, without special Unicode comparison algorithms.
New in version 2.1.
By default, the decoder expects an array or object as the input. With this flag enabled, the decoder accepts any valid JSON value.
Note: Decoding any value may be useful in some scenarios, but it’s generally discouraged as it violates strict compatiblity with RFC 4627. If you use this flag, don’t expect interoperatibility with other JSON systems.
New in version 2.3.
By default, the decoder expects that its whole input constitutes a valid JSON text, and issues an error if there’s extra data after the otherwise valid JSON input. With this flag enabled, the decoder stops after decoding a valid JSON array or object, and thus allows extra data after the JSON text.
Normally, reading will stop when the last ] or } in the JSON input is encountered. If both JSON_DISABLE_EOF_CHECK and JSON_DECODE_ANY flags are used, the decoder may read one extra UTF-8 code unit (up to 4 bytes of input). For example, decoding 4true correctly decodes the integer 4, but also reads the t. For this reason, if reading multiple consecutive values that are not arrays or objects, they should be separated by at least one whitespace character.
New in version 2.1.
Each function also takes an optional :type:`json_error_t` parameter that is filled with error information if decoding fails. It’s also updated on success; the number of bytes of input read is written to its position field. This is especially useful when using JSON_DISABLE_EOF_CHECK to read multiple consecutive JSON texts.
New in version 2.3: Number of bytes of input read is written to the position field of the :type:`json_error_t` structure.
If no error or position information is needed, you can pass NULL.
The following functions perform the actual JSON decoding.
Decodes the JSON string input and returns the array or object it contains, or NULL on error, in which case error is filled with information about the error. flags is described above.
Decodes the JSON string buffer, whose length is buflen, and returns the array or object it contains, or NULL on error, in which case error is filled with information about the error. This is similar to json_loads() except that the string doesn’t need to be null-terminated. flags is described above.
New in version 2.1.
Decodes the JSON text in stream input and returns the array or object it contains, or NULL on error, in which case error is filled with information about the error. flags is described above.
This function will start reading the input from whatever position the input file was, without attempting to seek first. If an error occurs, the file position will be left indeterminate. On success, the file position will be at EOF, unless JSON_DISABLE_EOF_CHECK flag was used. In this case, the file position will be at the first character after the last ] or } in the JSON input. This allows calling json_loadf() on the same FILE object multiple times, if the input consists of consecutive JSON texts, possibly separated by whitespace.
Decodes the JSON text in file path and returns the array or object it contains, or NULL on error, in which case error is filled with information about the error. flags is described above.
Decodes the JSON text produced by repeated calls to callback, and returns the array or object it contains, or NULL on error, in which case error is filled with information about the error. data is passed through to callback on each call. flags is described above.
New in version 2.4.
This section describes functions that help to create, or pack, complex JSON values, especially nested objects and arrays. Value building is based on a format string that is used to tell the functions about the expected arguments.
For example, the format string "i" specifies a single integer value, while the format string "[ssb]" or the equivalent "[s, s, b]" specifies an array value with two strings and a boolean as its items:
/* Create the JSON integer 42 */
json_pack("i", 42);
/* Create the JSON array ["foo", "bar", true] */
json_pack("[ssb]", "foo", "bar", 1);
Here’s the full list of format characters. The type in parentheses denotes the resulting JSON type, and the type in brackets (if any) denotes the C type that is expected as the corresponding argument.
Whitespace, : and , are ignored.
The following functions compose the value building API:
Build a new JSON value according to the format string fmt. For each format character (except for {}[]n), one argument is consumed and used to build the corresponding value. Returns NULL on error.
Like json_pack(), but an in the case of an error, an error message is written to error, if it’s not NULL. The flags parameter is currently unused and should be set to 0.
As only the errors in format string (and out-of-memory errors) can be caught by the packer, these two functions are most likely only useful for debugging format strings.
More examples:
/* Build an empty JSON object */
json_pack("{}");
/* Build the JSON object {"foo": 42, "bar": 7} */
json_pack("{sisi}", "foo", 42, "bar", 7);
/* Like above, ':', ',' and whitespace are ignored */
json_pack("{s:i, s:i}", "foo", 42, "bar", 7);
/* Build the JSON array [[1, 2], {"cool": true}] */
json_pack("[[i,i],{s:b}]", 1, 2, "cool", 1);
This sectinon describes functions that help to validate complex values and extract, or unpack, data from them. Like building values, this is also based on format strings.
While a JSON value is unpacked, the type specified in the format string is checked to match that of the JSON value. This is the validation part of the process. In addition to this, the unpacking functions can also check that all items of arrays and objects are unpacked. This check be enabled with the format character ! or by using the flag JSON_STRICT. See below for details.
Here’s the full list of format characters. The type in parentheses denotes the JSON type, and the type in brackets (if any) denotes the C type whose address should be passed.
Convert each item in the JSON object according to the inner format string fmt. The first, third, etc. format character represent a key, and must be s. The corresponding argument to unpack functions is read as the object key. The second fourth, etc. format character represent a value and is written to the address given as the corresponding argument. Note that every other argument is read from and every other is written to.
fmt may contain objects and arrays as values, i.e. recursive value extraction is supporetd.
New in version 2.3: Any s representing a key may be suffixed with a ? to make the key optional. If the key is not found, nothing is extracted. See below for an example.
Whitespace, : and , are ignored.
The following functions compose the parsing and validation API:
Note
The first argument of all unpack functions is json_t *root instead of const json_t *root, because the use of O format character causes the reference count of root, or some value reachable from root, to be increased. Furthermore, the o format character may be used to extract a value as-is, which allows modifying the structure or contents of a value reachable from root.
If the O and o format characters are not used, it’s perfectly safe to cast a const json_t * variable to plain json_t * when used with these functions.
The following unpacking flags are available:
Examples:
/* root is the JSON integer 42 */
int myint;
json_unpack(root, "i", &myint);
assert(myint == 42);
/* root is the JSON object {"foo": "bar", "quux": true} */
const char *str;
int boolean;
json_unpack(root, "{s:s, s:b}", "foo", &str, "quux", &boolean);
assert(strcmp(str, "bar") == 0 && boolean == 1);
/* root is the JSON array [[1, 2], {"baz": null} */
json_error_t error;
json_unpack_ex(root, &error, JSON_VALIDATE_ONLY, "[[i,i], {s:n}]", "baz");
/* returns 0 for validation success, nothing is extracted */
/* root is the JSON array [1, 2, 3, 4, 5] */
int myint1, myint2;
json_unpack(root, "[ii!]", &myint1, &myint2);
/* returns -1 for failed validation */
/* root is an empty JSON object */
int myint = 0, myint2 = 0;
json_unpack(root, "{s?i, s?[ii]}",
"foo", &myint1,
"bar", &myint2, &myint3);
/* myint1, myint2 or myint3 is no touched as "foo" and "bar" don't exist */
Testing for equality of two JSON values cannot, in general, be achieved using the == operator. Equality in the terms of the == operator states that the two :type:`json_t` pointers point to exactly the same JSON value. However, two JSON values can be equal not only if they are exactly the same value, but also if they have equal “contents”:
The following function can be used to test whether two JSON values are equal.
Because of reference counting, passing JSON values around doesn’t require copying them. But sometimes a fresh copy of a JSON value is needed. For example, if you need to modify an array, but still want to use the original afterwards, you should take a copy of it first.
Jansson supports two kinds of copying: shallow and deep. There is a difference between these methods only for arrays and objects. Shallow copying only copies the first level value (array or object) and uses the same child values in the copied value. Deep copying makes a fresh copy of the child values, too. Moreover, all the child values are deep copied in a recursive fashion.
Returns a shallow copy of value, or NULL on error.
Returns a deep copy of value, or NULL on error.
By default, Jansson uses malloc() and free() for memory allocation. These functions can be overridden if custom behavior is needed.
Examples:
Use the Boehm’s conservative garbage collector for memory operations:
json_set_alloc_funcs(GC_malloc, GC_free);
Allow storing sensitive data (e.g. passwords or encryption keys) in JSON structures by zeroing all memory when freed:
static void *secure_malloc(size_t size)
{
/* Store the memory area size in the beginning of the block */
void *ptr = malloc(size + 8);
*((size_t *)ptr) = size;
return ptr + 8;
}
static void secure_free(void *ptr)
{
size_t size;
ptr -= 8;
size = *((size_t *)ptr);
guaranteed_memset(ptr, 0, size);
free(ptr);
}
int main()
{
json_set_alloc_funcs(secure_malloc, secure_free);
/* ... */
}
For more information about the issues of storing sensitive data in memory, see http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/protect-secrets.html. The page also explains the guaranteed_memset() function used in the example and gives a sample implementation for it.