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.
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.
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.
intjsonGetType(Json *json, int nid, cchar *key)
 Get the value type for a node.
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*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 *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.
voidjsonToBuf(RBuf *buf, cchar *value, int flags)
 Convert a json value to serialized JSON representation and save in the given buffer.
RHash*jsonToHash(Json *json, int nid, cchar *key, RHash *hash)
 Convert a json sub-tree into a hash.
char*jsonToString(Json *json, int nid, cchar *key, int flags)
 Serialize a JSON object into a string.

Typedefs

JsonNodeJSON Node.

Defines

#defineITERATE_JSON    nid = (int) ((parent ? parent : json->nodes) - json->nodes + 1); \ (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_CCREATE   0x10
 Conditional create if not already existing '?'.
#defineJSON_COMBINE   0x1
 Combine properies using '+' '-' '=' '?' prefixes.
#defineJSON_OVERWRITE   0x2
 Default to overwrite existing properies '='.
#defineJSON_PASS_JSON   0x8
 Json allocated as part of an API call.
#defineJSON_PASS_TEXT   0x4
 Transfer ownership of the parsed text to json.
#defineJSON_PRETTY   0x10
 Save in Json6 format without quotes arounds keys.
#defineJSON_PRIMITIVE   0x10
 True, false, null, undefined, number.
#defineJSON_QUOTES   0x20
 Save in strict JSON format.
#defineJSON_REGEXP   0x20
 Regular expressions.
#defineJSON_REPLACE   0x8
 Replace existing properies '-'.
#defineJSON_SINGLE   0x2
 Save objects on a sinle line where possible.
#defineJSON_STRICT   0x1
 Expect strict JSON format.

Json

Json

JSON Object.

API Stability:
Prototype.
See Also:
Fields:
uintallocated Json object allocated as part of an API call.
uintcount Number of allocated nodes (count <= size).
char *end End of text + 1.
char *errorMsg Parsing error details.
REventevent Saving event.
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.

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.
See Also:

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 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.
See Also:

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.
See Also:

void jsonFree (Json *json)

Free a json object.

Parameters:
jsonA json object.
API Stability:
Evolving.
See Also:

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

Get a json node value as a string.

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". See rQueryJson for a full description of key formats.
defaultValueIf the key is not defined, return the defaultValue.
Returns:
The key value as a string or defaultValue if not defined.
API Stability:
Evolving.
See Also:

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". See rQueryJson for a full description of key formats.
defaultValueIf the key is not defined, return the defaultValue.
Returns:
The key value as a boolean or defaultValue if not defined.
API Stability:
Evolving.
See Also:

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.
See Also:

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". See rQueryJson for a full description of key formats.
Returns:
The node ID for the specified key.
API Stability:
Evolving.
See Also:

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". See rQueryJson for a full description of key formats.
defaultValueIf the key is not defined, return the defaultValue.
Returns:
The key value as an integer or defaultValue if not defined.
API Stability:
Evolving.
See Also:

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

Get a json node object.

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". See rQueryJson for a full description of key formats.
Returns:
The node object for the specified key. Returns NULL if not found.
API Stability:
Evolving.
See Also:

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". See rQueryJson for a full description of key formats.
Returns:
The data type. Set to JSON_OBJECT, JSON_ARRAY, JSON_COMMENT, JSON_STRING, JSON_PRIMITIVE or JSON_REGEXP.
API Stability:
Evolving.
See Also:

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.
Returns:
Json object if successful. Caller must free via jsonFree. Returns null if the text will not parse.
API Stability:
Evolving.
See Also:

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:
Prototype.
See Also:

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:
Prototype.
See Also:

void jsonPrint (Json *json)

Print a JSON object.

Description:
Prints a JSON object in pretty format.
Parameters:
jsonSource json.
API Stability:
Prototype.
See Also:

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". See rQueryJson for a full description of key formats.
Returns:
Returns a JSON object array of all removed properies. Array will be empty if not qualifying properies were found and removed.
API Stability:
Prototype.
See Also:

int jsonSave (Json *obj, int nid, 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.
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:
Prototype.
See Also:

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 multipar Property name and will operate at any level of depth in the JSON object. This routine supports the rQueryJson key syntax.
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 "." and the full rQueryJson syntax. For example: "settings.mode". See rQueryJson for a full description of key formats.
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:
Prototype.
See Also:

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.
See Also:

RHash * jsonToHash (Json *json, int nid, cchar *key, RHash *hash)

Convert a json sub-tree into a hash.

Description:
Converts the sub-tree rooted at the supplied key into the given hash table.
Parameters:
jsonSource json.
nidBase node ID from which to start the search.
keyProperty name to search for. This may include ".". For example: "settings.mode". See rQueryJson for a full description of key formats.
hashHash table to use for the result.
Returns:
The supplied hash table.
API Stability:
Evolving.
See Also:

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". See rQueryJson for a full description of key formats.
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.
Returns:
Returns a serialized JSON character string. Caller must free.
API Stability:
Prototype.
See Also:

Typedefs

JsonNode

JSON Node.

API Stability:
Prototype.
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.