libmj is a small library interface to allow JSON text to be created and parsed. JSON is the Java Script Object Notation, a lightweight data-interchange format, standardised in the ECMA standard. The library name
libmj is derived from a further acronym of “minimalist JSON”.
The
libmj library can be used to create a string in memory which contains a textual representation of a number of objects, arbitrarily structured. The library can also be used to reconstruct the structure. Data can thus be serialised easily and efficiently, and data structures rebuilt to produce the original structure of the data.
JSON contains basic units called atoms, the two basic atoms being strings and numbers. Three other useful atomic values are provided, “null”, “false”, and “true”. Atoms can be grouped together as key/value pairs in an “object”, and as individual, ordered atoms, in an “array”.
To create a new object, the
mj_create() is used. It can be deleted using the
mj_delete() function.
Atoms, objects and arrays can be appended to arrays and objects using the
mj_append() function.
Objects can be printed out by using the
mj_snprint() function. The size of a string of JSON text can be calculated using the
mj_string_size() function. A utility function
mj_asprint() is provided which will allocate space dynamically, using
calloc(3), and the JSON serialised text is copied into it. This memory can later be de-allocated using
free(3). For formatted output to a
FILE * stream, the
mj_pretty() function is used. The calling interface gives the ability to indent the output to a given
depth and for the formatted output to be followed by a
trailer string, which is usually
NULL for external calls, but can be any valid string. Output is sent to the
stream file stream.
The
type argument given to the
mj_create(),
mj_append(), and
mj_append_field() functions is taken from a list of “false” “true” “null” “number” “integer” “string” “array” and “object” types. An integer differs from a number in that it cannot take on any floating point values. It is implemented internally using a signed 64-bit integer type. This restriction of values for an integer type may be removed at a later date.
Within a JSON object, the key values can be iterated over using an integer index to access the individual JSON objects. The index can also be found using the
mj_object_find() function.
The way objects arrays are implemented in
libmj is by using varying-sized arrays internally. Objects have the field name as the even entry in this internal array, with the value being the odd entry. Arrays are implemented as a simple array. Thus, to find an object in an array using
mj_object_find(), a value of 1 should be used as the increment value. This means that every entry in the internal array will be examined, and the first match after the starting point will be returned. For objects, an incremental value of 2 should be used, and an even start value should be specified.