Skip to content

JSON API

The JSON library provides JSON parsing, serialization and query capabilities. The library can parse strings and read files containing JSON text.

JSON can be read and serialized in strict JSON or in the more human readable JSON/5 format. When parsed, JSON is stored in-memory in a binary search tree for efficient querying. The library supports searching, querying and updating JSON values using dot and array notation.

The library supports the JSON and JSON/5 formats. JSON/5 is an extension of JSON that makes it easier to create, read and maintain configuration files in JSON. JSON/5 supports the following features to JSON:

  • Object keys may be JavaScript identifiers without quotes.
  • Objects or arrays may have a trailing comma.
  • Strings may be single quoted.
  • Strings may span multiple lines (single, double or back-tick quotes).
  • Numbers may have a leading or trailing decimal point, be hexadecimal, may begin with a plus
  • Values may be regular expressions.
  • Undefined is a valid value.
  • Single and multiline comments are allowed and preserved.

Extensions

Json JSON Object.

Functions

Json *jsonAlloc(int flags)
 Allocate a json object.
intjsonBlend(Json *dest, int did, cchar *dkey, Json *src, int sid, cchar *skey, int flags)
 Blend nodes by copying from one Json to another.
Json *jsonClone(Json *src, int flags)
 Clone a json object.
char *jsonFmtToString(cchar *fmt, ...)
 Format a string into strict json and return a strict JSON formatted string.
voidjsonFree(Json *json)
 Free a json object.
cchar *jsonGet(Json *json, int nid, cchar *key, cchar *defaultValue)
 Get a json node value as a string.
booljsonGetBool(Json *json, int nid, cchar *key, bool defaultValue)
 Get a json node value as a boolean.
JsonNode *jsonGetChildNode(Json *json, int nid, int nth)
 Get the Nth child node for a json node.
char *jsonGetClone(Json *json, int nid, cchar *key, cchar *defaultValue)
 Get a json node value as an allocated string.
intjsonGetId(Json *json, int nid, cchar *key)
 Get a json node ID.
intjsonGetInt(Json *json, int nid, cchar *key, int defaultValue)
 Get a json node value as an integer.
JsonNode *jsonGetNode(Json *json, int nid, cchar *key)
 Get a json node object.
int64jsonGetNum(Json *json, int nid, cchar *key, int64 defaultValue)
 Get a json node value as a 64-bit integer.
cchar *jsonGetRef(Json *json, int nid, cchar *key, cchar *defaultValue)
 Get a json node value as a string.
intjsonGetType(Json *json, int nid, cchar *key)
 Get the value type for a node.
voidjsonLock(Json *json)
 Lock a json object from further updates.
Json *jsonParse(cchar *text, int flags)
 Parse a json string into a json object.
Json *jsonParseFile(cchar *path, char **errorMsg, int flags)
 Load a JSON object from a filename.
Json *jsonParseFmt(cchar *fmt, ...)
 Parse a formatted string into a json object.
Json *jsonParseString(cchar *text, char **errorMsg, int flags)
 Parse a JSON string into an object tree and return any errors.
voidjsonPrint(Json *json)
 Print a JSON object.
intjsonRemove(Json *obj, int nid, cchar *key)
 Remove a Property from a JSON object.
intjsonSave(Json *obj, int nid, cchar *key, cchar *path, int mode, int flags)
 Save a JSON object to a filename.
intjsonSet(Json *obj, int nid, cchar *key, cchar *value, int type)
 Update a key/value in the JSON object with a string value.
intjsonSetBool(Json *obj, int nid, cchar *key, bool value)
 Update a property in the JSON object with a boolean value.
intjsonSetDate(Json *json, int nid, cchar *key, Time value)
 Update a property in the JSON object with date value.
intjsonSetDouble(Json *json, int nid, cchar *key, double value)
 Update a property with a floating point number value.
intjsonSetFmt(Json *obj, int nid, cchar *key, cchar *fmt, ...)
 Update a key/value in the JSON object with a formatted string value.
voidjsonSetNodeType(JsonNode *node, int type)
 Update a node type.
voidjsonSetNodeValue(JsonNode *node, cchar *value, int type, int flags)
 Directly update a node value.
intjsonSetNumber(Json *json, int nid, cchar *key, int64 value)
 Update a property in the JSON object with a numeric value.
cchar *jsonString(Json *json)
 Serialize an entire JSON object into a string using a human readable format (JSON_PRETTY).
char *jsonTemplate(Json *json, cchar *str)
 Expand a string template with ${prop.prop...} references.
voidjsonToBuf(RBuf *buf, cchar *value, int flags)
 Convert a json value to serialized JSON representation and save in the given buffer.
char *jsonToString(Json *json, int nid, cchar *key, int flags)
 Serialize a JSON object into a string.
voidjsonUnlock(Json *json)
 Unlock a json object to allow updates.

Typedefs

JsonNodeJSON Node.

Defines

#defineITERATE_JSON    nid = (int) ((parent ? parent : json->nodes) - json->nodes + 1); \ (json->count > 0) && json->nodes && (nid < (parent ? parent : json->nodes)->last) && \ ((child = &json->nodes[nid]) != 0); \ nid = child->last
 This iterates over the children under the "parent" id.
#defineJSON_APPEND   0x4
 Default to append to existing '+' (default).
#defineJSON_BARE   0x1000
 Save on a single line without quotes or [].
#defineJSON_CCREATE   0x10
 Conditional create if not already existing '?'.
#defineJSON_COMBINE   0x1
 Combine properies using '+' '-' '=' '?' prefixes.
#defineJSON_LOCK   0x1
 Lock JSON object from further object.
#defineJSON_OVERWRITE   0x2
 Default to overwrite existing properies '='.
#defineJSON_PASS_TEXT   0x40
 Transfer ownership of the parsed text to json.
#defineJSON_PRETTY   0x100
 Save in Json6 format without quotes arounds keys.
#defineJSON_PRIMITIVE   0x10
 True, false, null, undefined, number.
#defineJSON_QUOTES   0x200
 Save in strict JSON format.
#defineJSON_REGEXP   0x20
 Regular expressions.
#defineJSON_REMOVE_UNDEF   0x20
 Remove undefined (NULL) properties.
#defineJSON_REPLACE   0x8
 Replace existing properies '-'.
#defineJSON_SINGLE   0x20
 Save objects on a sinle line where possible.
#defineJSON_STRICT   0x10
 Expect strict JSON format.
#defineJSON_STRING   0x8
 Strings including dates encoded as ISO strings.
#defineJSON_USER_ALLOC   0x2
 User flag to indicate who allocated the json obj.

Json

Json

JSON Object.

Description:
The JSON library parses JSON strings into an in-memory JSON tree that can be queried and modified and saved. Some APIs such as jsonGetRef return direct references into the JSON tree for performance as (const char*) references. Others, such as jsonGet will return an allocated string that must be freed by the caller.
When a JSON object is allocated or parsed, the JSON tree may be locked via the JSON_LOCK flag. A locked JSON object is useful as it will not permit further updates via (jsonSet or jsonBlend) and the internal node structure will be stable such that references returned via jsonGetRef and jsonGetNode will remain valid.
API Stability:
Evolving.
Fields:
uintcount Number of allocated nodes (count <= size).
char *end End of text + 1.
char *errorMsg Parsing error details.
uintflags Use defined bits.
uintlineNumber Current parse line number.
char *next Pointer to next token.
char *path Filename being parsed.
uintsize Size of Json.nodes in elements (includes spare).
uintstrict Strict JSON standard mode.
char *text Text being parsed.
char *value Result from jsonString.

Json * * jsonAlloc (int flags)

Allocate a json object.

Parameters:
flagsSet to one JSON_STRICT for strict JSON parsing. Otherwise permits JSON/5.
Returns:
A json object.
API Stability:
Evolving.

int jsonBlend (Json *dest, int did, cchar *dkey, Json *src, int sid, cchar *skey, int flags)

Blend nodes by copying from one Json to another.

Description:
This performs an N-level deep clone of the source JSON nodes to be blended into the destination object. By default, this add new object properies and overwrite arrays and string values. The Property combination prefixes: '+', '=', '-' and '?' to append, overwrite, replace and conditionally overwrite are supported if the JSON_COMBINE flag is present.
Parameters:
destDestination json.
didBase node ID from which to store the copied nodes.
dkeyDestination property name to search for.
srcSource json.
sidBase node ID from which to copy nodes.
skeySource property name to search for.
flagsThe JSON_COMBINE flag enables Property name prefixes: '+', '=', '-', '?' to append, overwrite, replace and conditionally overwrite key values if not already present. When adding string properies, values will be appended using a space separator. Extra spaces will not be removed on replacement.

Without JSON_COMBINE or for properies without a prefix, the default is to blend objects by creating new properies if not already existing in the destination, and to treat overwrite arrays and strings. Use the JSON_OVERWRITE flag to override the default appending of objects and rather overwrite existing properies. Use the JSON_APPEND flag to override the default of overwriting arrays and strings and rather append to existing properies.
Returns:
Zero if successful.
API Stability:
Evolving.

Json * * jsonClone (Json *src, int flags)

Clone a json object.

Parameters:
srcInput json object.
flagsReserved, set to zero.
Returns:
The copied JSON tree. Caller must free with jsonFree
API Stability:
Evolving.

char * * jsonFmtToString (cchar *fmt, ...)

Format a string into strict json and return a strict JSON formatted string.

Parameters:
fmtPrintf style format string.
...Args for format.
Returns:
A string. Caller must free.
API Stability:
Evolving.

void jsonFree (Json *json)

Free a json object.

Parameters:
jsonA json object.
API Stability:
Evolving.

cchar * * jsonGet (Json *json, int nid, cchar *key, cchar *defaultValue)

Get a json node value as a string.

Description:
This call returns a reference into the JSON storage. Such references are short-term and may not remain valid if other modifications are made to the JSON tree. Only use the result of this API while no other changes are made to the JSON object. Use jsonGet if you need to retain the queried value.
Parameters:
jsonSource json.
nidBase node ID from which to examine. Set to zero for the top level.
keyProperty name to search for. This may include ".". For example: "settings.mode".
defaultValueIf the key is not defined, return the defaultValue.
Returns:
The key value as a string or defaultValue if not defined. This is a reference into the JSON store. Caller must NOT free.
API Stability:
Evolving.

bool jsonGetBool (Json *json, int nid, cchar *key, bool defaultValue)

Get a json node value as a boolean.

Parameters:
jsonSource json.
nidBase node ID from which to examine. Set to zero for the top level.
keyProperty name to search for. This may include ".". For example: "settings.mode".
defaultValueIf the key is not defined, return the defaultValue.
Returns:
The key value as a boolean or defaultValue if not defined.
API Stability:
Evolving.

JsonNode * * jsonGetChildNode (Json *json, int nid, int nth)

Get the Nth child node for a json node.

Parameters:
jsonSource json.
nidBase node ID to examine.
nthSpecify which child to return.
Returns:
The Nth child node object for the specified node.
API Stability:
Evolving.

char * * jsonGetClone (Json *json, int nid, cchar *key, cchar *defaultValue)

Get a json node value as an allocated string.

Description:
This call returns an allocated string as the result. Use jsonGetRef as a higher performance API if you do not need to retain the queried value.
Parameters:
jsonSource json.
nidBase node ID from which to examine. Set to zero for the top level.
keyProperty name to search for. This may include ".". For example: "settings.mode".
defaultValueIf the key is not defined, return a copy of the defaultValue. The defaultValue can be NULL in which case the return value will be an allocated empty string.
Returns:
An allocated string copy of the key value or defaultValue if not defined. Caller must free.
API Stability:
Evolving.

int jsonGetId (Json *json, int nid, cchar *key)

Get a json node ID.

Parameters:
jsonSource json.
nidBase node ID from which to start the search. Set to zero for the top level.
keyProperty name to search for. This may include ".". For example: "settings.mode".
Returns:
The node ID for the specified key.
API Stability:
Evolving.

int jsonGetInt (Json *json, int nid, cchar *key, int defaultValue)

Get a json node value as an integer.

Parameters:
jsonSource json.
nidBase node ID from which to examine. Set to zero for the top level.
keyProperty name to search for. This may include ".". For example: "settings.mode".
defaultValueIf the key is not defined, return the defaultValue.
Returns:
The key value as an integer or defaultValue if not defined.
API Stability:
Evolving.

JsonNode * * jsonGetNode (Json *json, int nid, cchar *key)

Get a json node object.

Description:
This call returns a reference into the JSON storage. Such references are not persistent if other modifications are made to the JSON tree.
Parameters:
jsonSource json.
nidBase node ID from which to start the search. Set to zero for the top level.
keyProperty name to search for. This may include ".". For example: "settings.mode".
Returns:
The node object for the specified key. Returns NULL if not found.
API Stability:
Evolving.

int64 jsonGetNum (Json *json, int nid, cchar *key, int64 defaultValue)

Get a json node value as a 64-bit integer.

Parameters:
jsonSource json.
nidBase node ID from which to examine. Set to zero for the top level.
keyProperty name to search for. This may include ".". For example: "settings.mode".
defaultValueIf the key is not defined, return the defaultValue.
Returns:
The key value as a 64-bit integer or defaultValue if not defined.
API Stability:
Evolving.

cchar * * jsonGetRef (Json *json, int nid, cchar *key, cchar *defaultValue)

Get a json node value as a string.

Description:
This call is deprecated. Use jsonGet or jsonGetClone instead. This call returns a reference into the JSON storage. Such references are short-term and may not remain valid if other modifications are made to the JSON tree. Only use the result of this API while no other changes are made to the JSON object. Use jsonGet if you need to retain the queried value.
Parameters:
jsonSource json.
nidBase node ID from which to examine. Set to zero for the top level.
keyProperty name to search for. This may include ".". For example: "settings.mode".
defaultValueIf the key is not defined, return the defaultValue.
Returns:
The key value as a string or defaultValue if not defined. This is a reference into the JSON store. Caller must NOT free.
API Stability:
Deprecated.

int jsonGetType (Json *json, int nid, cchar *key)

Get the value type for a node.

Parameters:
jsonSource json.
nidBase node ID from which to start the search.
keyProperty name to search for. This may include ".". For example: "settings.mode".
Returns:
The data type. Set to JSON_OBJECT, JSON_ARRAY, JSON_COMMENT, JSON_STRING, JSON_PRIMITIVE or JSON_REGEXP.
API Stability:
Evolving.

void jsonLock (Json *json)

Lock a json object from further updates.

Description:
This call is useful to block all further updates via jsonSet. The jsonGet API returns a references into the JSON tree. Subsequent updates can grow the internal JSON structures and thus move references returned earlier.
Parameters:
jsonA json object.
API Stability:
Evolving.

Json * * jsonParse (cchar *text, int flags)

Parse a json string into a json object.

Description:
Use this method if you are sure the supplied JSON text is valid. Use jsonParseString if you need to receive notification of parse errors.
Parameters:
textJson string to parse.
flagsSet to JSON_STRICT to parse json, otherwise a relaxed json6 syntax is supported. Set JSON_PASS_TEXT to transfer ownership of the text to json which will free when jsonFree is called. Set to JSON_LOCK to lock the JSON tree to prevent further modification via jsonSet or jsonBlend. This will make returned references via jsonGetRef and jsonGetNode stable.
Returns:
Json object if successful. Caller must free via jsonFree. Returns null if the text will not parse.
API Stability:
Evolving.

Json * * jsonParseFile (cchar *path, char **errorMsg, int flags)

Load a JSON object from a filename.

Parameters:
pathFilename path containing a JSON string to load.
errorMsgError message string set if the parse fails. Caller must not free.
flagsSet to JSON_STRICT to parse json, otherwise a relaxed json6 syntax is supported.
Returns:
JSON object tree. Caller must free errorMsg via rFree on errors.
API Stability:
Evolving.

Json * * jsonParseFmt (cchar *fmt, ...)

Parse a formatted string into a json object.

Parameters:
fmtPrintf style format string.
...Args for format.
Returns:
A json object. Caller must free.
API Stability:
Evolving.

Json * * jsonParseString (cchar *text, char **errorMsg, int flags)

Parse a JSON string into an object tree and return any errors.

Description:
Deserializes a JSON string created into an object. The top level of the JSON string must be an object, array, string, number or boolean value.
Parameters:
textJSON string to deserialize.
errorMsgError message string set if the parse fails. Caller must not free.
flagsSet to JSON_STRICT to parse json, otherwise a relaxed json6 syntax is supported. Set JSON_PASS_TEXT to transfer ownership of the text to json which will free when jsonFree is called.
Returns:
Returns a tree of Json objects. Each object represents a level in the JSON input stream. Caller must free errorMsg via rFree on errors.
API Stability:
Evolving.

void jsonPrint (Json *json)

Print a JSON object.

Description:
Prints a JSON object in pretty format.
Parameters:
jsonSource json.
API Stability:
Evolving.

int jsonRemove (Json *obj, int nid, cchar *key)

Remove a Property from a JSON object.

Parameters:
objParsed JSON object returned by jsonParse.
nidBase node ID from which to start searching for key. Set to zero for the top level.
keyProperty name to remove for. This may include ".". For example: "settings.mode".
Returns:
Returns a JSON object array of all removed properies. Array will be empty if not qualifying properies were found and removed.
API Stability:
Evolving.

int jsonSave (Json *obj, int nid, cchar *key, cchar *path, int mode, int flags)

Save a JSON object to a filename.

Parameters:
objParsed JSON object returned by jsonParse.
nidBase node ID from which to start searching for key. Set to zero for the top level.
keyProperty name to add/update. This may include ".". For example: "settings.mode".
pathFilename path to contain the saved JSON string.
flagsSame flags as for jsonToString: JSON_PRETTY, JSON_QUOTES.
modePermissions mode.
Returns:
Zero if successful, otherwise a negative RT error code.
API Stability:
Evolving.

int jsonSet (Json *obj, int nid, cchar *key, cchar *value, int type)

Update a key/value in the JSON object with a string value.

Description:
This call takes a multipart Property name and will operate at any level of depth in the JSON object.
Parameters:
objParsed JSON object returned by jsonParse.
nidBase node ID from which to start search for key. Set to zero for the top level.
keyProperty name to add/update. This may include ".". For example: "settings.mode".
valueCharacter string value.
typeSet to JSON_ARRAY, JSON_OBJECT, JSON_PRIMITIVE or JSON_STRING.
Returns:
Positive node id if updated successfully. Otherwise a negative error code.
API Stability:
Evolving.

int jsonSetBool (Json *obj, int nid, cchar *key, bool value)

Update a property in the JSON object with a boolean value.

Description:
This call takes a multipart Property name and will operate at any level of depth in the JSON object.
Parameters:
objParsed JSON object returned by jsonParse.
nidBase node ID from which to start search for key. Set to zero for the top level.
keyProperty name to add/update. This may include ".". For example: "settings.mode".
valueBoolean string value.
Returns:
Positive node id if updated successfully. Otherwise a negative error code.
API Stability:
Evolving.

int jsonSetDate (Json *json, int nid, cchar *key, Time value)

Update a property in the JSON object with date value.

Description:
This call takes a multipart Property name and will operate at any level of depth in the JSON object.
Parameters:
jsonParsed JSON object returned by jsonParse.
nidBase node ID from which to start search for key. Set to zero for the top level.
keyProperty name to add/update. This may include ".". For example: "settings.mode".
valueDate value expressed as a Time (Elapsed milliseconds since Jan 1, 1970).
Returns:
Positive node id if updated successfully. Otherwise a negative error code.
API Stability:
Evolving.

int jsonSetDouble (Json *json, int nid, cchar *key, double value)

Update a property with a floating point number value.

Description:
This call takes a multipart Property name and will operate at any level of depth in the JSON object.
Parameters:
jsonParsed JSON object returned by jsonParse.
nidBase node ID from which to start search for key. Set to zero for the top level.
keyProperty name to add/update. This may include ".". For example: "settings.mode".
valueDouble floating point value.
Returns:
Positive node id if updated successfully. Otherwise a negative error code.
API Stability:
Evolving.

int jsonSetFmt (Json *obj, int nid, cchar *key, cchar *fmt, ...)

Update a key/value in the JSON object with a formatted string value.

Description:
The type of the inserted value is determined from the contents. This call takes a multipart property name and will operate at any level of depth in the JSON object.
Parameters:
objParsed JSON object returned by jsonParse.
nidBase node ID from which to start search for key. Set to zero for the top level.
keyProperty name to add/update. This may include ".". For example: "settings.mode".
fmtPrintf style format string.
...Args for format.
Returns:
Positive node id if updated successfully. Otherwise a negative error code.
API Stability:
Evolving.

void jsonSetNodeType (JsonNode *node, int type)

Update a node type.

Description:
This is an internal API and is subject to change without notice. It offers a higher performance path to update node types.
Parameters:
nodeJson node.
typeJson node type.
API Stability:
Internal.

void jsonSetNodeValue (JsonNode *node, cchar *value, int type, int flags)

Directly update a node value.

Description:
This is an internal API and is subject to change without notice. It offers a higher performance path to update node values.
Parameters:
nodeJson node.
valueString value to update with.
typeJson node type.
flagsSet to JSON_PASS_TEXT to transfer ownership of a string. JSON will then free.
API Stability:
Internal.

int jsonSetNumber (Json *json, int nid, cchar *key, int64 value)

Update a property in the JSON object with a numeric value.

Description:
This call takes a multipart Property name and will operate at any level of depth in the JSON object.
Parameters:
jsonParsed JSON object returned by jsonParse.
nidBase node ID from which to start search for key. Set to zero for the top level.
keyProperty name to add/update. This may include ".". For example: "settings.mode".
valueNumber to update.
Returns:
Positive node id if updated successfully. Otherwise a negative error code.
API Stability:
Evolving.

cchar * * jsonString (Json *json)

Serialize an entire JSON object into a string using a human readable format (JSON_PRETTY).

Parameters:
jsonSource json.
Returns:
Returns a serialized JSON character string. Caller must NOT free.
API Stability:
Evolving.

char * * jsonTemplate (Json *json, cchar *str)

Expand a string template with ${prop.prop...} references.

Parameters:
jsonJson object.
strString template to expand.
Returns:
An allocated expanded string. Caller must free.
API Stability:
Evolving.

void jsonToBuf (RBuf *buf, cchar *value, int flags)

Convert a json value to serialized JSON representation and save in the given buffer.

Parameters:
bufDestination buffer.
valueValue to convert.
flagsJson flags.
API Stability:
Evolving.

char * * jsonToString (Json *json, int nid, cchar *key, int flags)

Serialize a JSON object into a string.

Description:
Serializes a top level JSON object created via jsonParse into a characters string in JSON format.
Parameters:
jsonSource json.
nidBase node ID from which to convert. Set to zero for the top level.
keyProperty name to serialize below. This may include ".". For example: "settings.mode".
flagsSerialization flags. Supported flags include JSON_PRETTY for a human-readable multiline format. JSON_QUOTES to wrap Property names in quotes. Use JSON_QUOTES to emit all Property values as quoted strings. Defaults to JSON_PRETTY if set to zero.
Returns:
Returns a serialized JSON character string. Caller must free.
API Stability:
Evolving.

void jsonUnlock (Json *json)

Unlock a json object to allow updates.

Parameters:
jsonA json object.
API Stability:
Evolving.

Typedefs

JsonNode

JSON Node.

API Stability:
Evolving.
Fields:
uintallocatedName True if the node text was allocated and must be freed.
uintallocatedValue True if the node text was allocated and must be freed.
intlast Index +1 of last node for which this node is parent.
char *name Property name - null terminated.
uinttype Primitive type of the node (object, array, string or primitive).
char *value Property value - null terminated.