cjson · Section 3
cjson_serialize
NAME
cjson_serialize - serialize a DOM tree to a compact JSON string
LIBRARY
C Collections (libccollections, -lccollections)
SYNOPSIS
#include <ccollections/cjson.h> char *cjson_serialize(cjson node);
DESCRIPTION
Walks the DOM tree under node and writes it as a compact JSON string with no whitespace. A NULL node gives the string "null". Object members come out in insertion order (see cjson_dictionary_first(3)) and array elements in index order, so one tree gives the same output on every call and in every process. A document that is parsed and serialized again keeps the order of its members. A double is written in the shortest decimal form that reads back as the same value, which has at most 17 significant digits. The decimal separator is always '.', as RFC 8259 asks, whatever the LC_NUMERIC locale of the calling thread. An integer is written with %lld, and a double that is not finite (Inf and NaN) as "null". The output is always valid JSON text. Every string in a tree, value or object key, is well-formed UTF-8, because the library checks that wherever bytes enter a tree (see cjson_parse(3) and cjson_create_string(3)). So the serializer writes string content unchanged and adds only the escapes that JSON itself needs. A subtree that nests more than 500 levels deep is refused and the function returns NULL for it. Each array or object counts as one level, in any combination, and a scalar adds none. The parser has the same limit, and only the construction API (cjson_list_push() and cjson_dictionary_set()) can build a deeper tree, since it has no depth bound of its own. The limit is a policy and has nothing to do with the stack size of the calling thread: The serializer walks the nesting with an explicit worklist on the heap, so a tree at the limit uses the same small, fixed amount of native stack as a flat one. An ordinary tree never comes near this depth.
RETURN VALUE
On success, a null-terminated string on the heap. NULL when an allocation fails or when node nests more than 500 levels deep. The string comes from the root node's allocator. When the default allocator built the tree, the caller frees it with cjson_serialize_free(), and when a custom allocator built it, with cjson_serialize_free_mp() and that same allocator. Calling cjson_serialize_free() on a buffer from a custom allocator hands it to plain free(), which never allocated it.
SEE ALSO
cjson_serialize_pretty(3), cjson_serialize_free(3), cjson_serialize_free_mp(3), cjson_create_string(3), cjson_dictionary_first(3), cjson_parse(3)