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. | |
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. | |
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. | |
void | jsonFree(Json *json) |
Free a json object. | |
cchar * | jsonGet(Json *json, int nid, cchar *key, cchar *defaultValue) |
Get a json node value as a string. | |
bool | jsonGetBool(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. | |
int | jsonGetId(Json *json, int nid, cchar *key) |
Get a json node ID. | |
int | jsonGetInt(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. | |
int64 | jsonGetNum(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. | |
int | jsonGetType(Json *json, int nid, cchar *key) |
Get the value type for a node. | |
void | jsonLock(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. | |
void | jsonPrint(Json *json) |
Print a JSON object. | |
int | jsonRemove(Json *obj, int nid, cchar *key) |
Remove a Property from a JSON object. | |
int | jsonSave(Json *obj, int nid, cchar *key, cchar *path, int mode, int flags) |
Save a JSON object to a filename. | |
int | jsonSet(Json *obj, int nid, cchar *key, cchar *value, int type) |
Update a key/value in the JSON object with a string value. | |
int | jsonSetBool(Json *obj, int nid, cchar *key, bool value) |
Update a property in the JSON object with a boolean value. | |
int | jsonSetDate(Json *json, int nid, cchar *key, Time value) |
Update a property in the JSON object with date value. | |
int | jsonSetDouble(Json *json, int nid, cchar *key, double value) |
Update a property with a floating point number value. | |
int | jsonSetFmt(Json *obj, int nid, cchar *key, cchar *fmt, ...) |
Update a key/value in the JSON object with a formatted string value. | |
void | jsonSetNodeType(JsonNode *node, int type) |
Update a node type. | |
void | jsonSetNodeValue(JsonNode *node, cchar *value, int type, int flags) |
Directly update a node value. | |
int | jsonSetNumber(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. | |
void | jsonToBuf(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. | |
void | jsonUnlock(Json *json) |
Unlock a json object to allow updates. |
Typedefs
JsonNode | JSON Node. |
Defines
#define | ITERATE_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. | |
#define | JSON_APPEND 0x4 |
Default to append to existing '+' (default). | |
#define | JSON_BARE 0x1000 |
Save on a single line without quotes or []. | |
#define | JSON_CCREATE 0x10 |
Conditional create if not already existing '?'. | |
#define | JSON_COMBINE 0x1 |
Combine properies using '+' '-' '=' '?' prefixes. | |
#define | JSON_LOCK 0x1 |
Lock JSON object from further object. | |
#define | JSON_OVERWRITE 0x2 |
Default to overwrite existing properies '='. | |
#define | JSON_PASS_TEXT 0x40 |
Transfer ownership of the parsed text to json. | |
#define | JSON_PRETTY 0x100 |
Save in Json6 format without quotes arounds keys. | |
#define | JSON_PRIMITIVE 0x10 |
True, false, null, undefined, number. | |
#define | JSON_QUOTES 0x200 |
Save in strict JSON format. | |
#define | JSON_REGEXP 0x20 |
Regular expressions. | |
#define | JSON_REMOVE_UNDEF 0x20 |
Remove undefined (NULL) properties. | |
#define | JSON_REPLACE 0x8 |
Replace existing properies '-'. | |
#define | JSON_SINGLE 0x20 |
Save objects on a sinle line where possible. | |
#define | JSON_STRICT 0x10 |
Expect strict JSON format. | |
#define | JSON_STRING 0x8 |
Strings including dates encoded as ISO strings. | |
#define | JSON_USER_ALLOC 0x2 |
User flag to indicate who allocated the json obj. |
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:
-
uint count Number of allocated nodes (count <= size). char * end End of text + 1. char * errorMsg Parsing error details. uint flags Use defined bits. uint lineNumber Current parse line number. char * next Pointer to next token. char * path Filename being parsed. uint size Size of Json.nodes in elements (includes spare). uint strict Strict JSON standard mode. char * text Text being parsed. char * value Result from jsonString.
Allocate a json object.
- Parameters:
-
flags Set to one JSON_STRICT for strict JSON parsing. Otherwise permits JSON/5.
- Returns:
- A json object.
- API Stability:
- Evolving.
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:
-
dest Destination json. did Base node ID from which to store the copied nodes. dkey Destination property name to search for. src Source json. sid Base node ID from which to copy nodes. skey Source property name to search for. flags The 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.
Clone a json object.
- Parameters:
-
src Input json object. flags Reserved, set to zero.
- Returns:
- The copied JSON tree. Caller must free with jsonFree
- API Stability:
- Evolving.
Format a string into strict json and return a strict JSON formatted string.
- Parameters:
-
fmt Printf style format string. ... Args for format.
- Returns:
- A string. Caller must free.
- API Stability:
- Evolving.
Free a json object.
- Parameters:
-
json A json object.
- API Stability:
- Evolving.
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:
-
json Source json. nid Base node ID from which to examine. Set to zero for the top level. key Property name to search for. This may include ".". For example: "settings.mode". defaultValue If 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.
Get a json node value as a boolean.
- Parameters:
-
json Source json. nid Base node ID from which to examine. Set to zero for the top level. key Property name to search for. This may include ".". For example: "settings.mode". defaultValue If the key is not defined, return the defaultValue.
- Returns:
- The key value as a boolean or defaultValue if not defined.
- API Stability:
- Evolving.
Get the Nth child node for a json node.
- Parameters:
-
json Source json. nid Base node ID to examine. nth Specify which child to return.
- Returns:
- The Nth child node object for the specified node.
- API Stability:
- Evolving.
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:
-
json Source json. nid Base node ID from which to examine. Set to zero for the top level. key Property name to search for. This may include ".". For example: "settings.mode". defaultValue If 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.
Get a json node ID.
- Parameters:
-
json Source json. nid Base node ID from which to start the search. Set to zero for the top level. key Property name to search for. This may include ".". For example: "settings.mode".
- Returns:
- The node ID for the specified key.
- API Stability:
- Evolving.
Get a json node value as an integer.
- Parameters:
-
json Source json. nid Base node ID from which to examine. Set to zero for the top level. key Property name to search for. This may include ".". For example: "settings.mode". defaultValue If the key is not defined, return the defaultValue.
- Returns:
- The key value as an integer or defaultValue if not defined.
- API Stability:
- Evolving.
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:
-
json Source json. nid Base node ID from which to start the search. Set to zero for the top level. key Property 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.
Get a json node value as a 64-bit integer.
- Parameters:
-
json Source json. nid Base node ID from which to examine. Set to zero for the top level. key Property name to search for. This may include ".". For example: "settings.mode". defaultValue If 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.
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:
-
json Source json. nid Base node ID from which to examine. Set to zero for the top level. key Property name to search for. This may include ".". For example: "settings.mode". defaultValue If 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.
Get the value type for a node.
- Parameters:
-
json Source json. nid Base node ID from which to start the search. key Property 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.
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:
-
json A json object.
- API Stability:
- Evolving.
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:
-
text Json string to parse. flags Set 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.
Load a JSON object from a filename.
- Parameters:
-
path Filename path containing a JSON string to load. errorMsg Error message string set if the parse fails. Caller must not free. flags Set 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.
Parse a formatted string into a json object.
- Parameters:
-
fmt Printf style format string. ... Args for format.
- Returns:
- A json object. Caller must free.
- API Stability:
- Evolving.
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:
-
text JSON string to deserialize. errorMsg Error message string set if the parse fails. Caller must not free. flags Set 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.
Print a JSON object.
- Description:
- Prints a JSON object in pretty format.
- Parameters:
-
json Source json.
- API Stability:
- Evolving.
Remove a Property from a JSON object.
- Parameters:
-
obj Parsed JSON object returned by jsonParse. nid Base node ID from which to start searching for key. Set to zero for the top level. key Property 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.
Save a JSON object to a filename.
- Parameters:
-
obj Parsed JSON object returned by jsonParse. nid Base node ID from which to start searching for key. Set to zero for the top level. key Property name to add/update. This may include ".". For example: "settings.mode". path Filename path to contain the saved JSON string. flags Same flags as for jsonToString: JSON_PRETTY, JSON_QUOTES. mode Permissions mode.
- Returns:
- Zero if successful, otherwise a negative RT error code.
- API Stability:
- Evolving.
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:
-
obj Parsed JSON object returned by jsonParse. nid Base node ID from which to start search for key. Set to zero for the top level. key Property name to add/update. This may include ".". For example: "settings.mode". value Character string value. type Set 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.
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:
-
obj Parsed JSON object returned by jsonParse. nid Base node ID from which to start search for key. Set to zero for the top level. key Property name to add/update. This may include ".". For example: "settings.mode". value Boolean string value.
- Returns:
- Positive node id if updated successfully. Otherwise a negative error code.
- API Stability:
- Evolving.
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:
-
json Parsed JSON object returned by jsonParse. nid Base node ID from which to start search for key. Set to zero for the top level. key Property name to add/update. This may include ".". For example: "settings.mode". value Date 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.
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:
-
json Parsed JSON object returned by jsonParse. nid Base node ID from which to start search for key. Set to zero for the top level. key Property name to add/update. This may include ".". For example: "settings.mode". value Double floating point value.
- Returns:
- Positive node id if updated successfully. Otherwise a negative error code.
- API Stability:
- Evolving.
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:
-
obj Parsed JSON object returned by jsonParse. nid Base node ID from which to start search for key. Set to zero for the top level. key Property name to add/update. This may include ".". For example: "settings.mode". fmt Printf style format string. ... Args for format.
- Returns:
- Positive node id if updated successfully. Otherwise a negative error code.
- API Stability:
- Evolving.
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:
-
node Json node. type Json node type.
- API Stability:
- Internal.
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:
-
node Json node. value String value to update with. type Json node type. flags Set to JSON_PASS_TEXT to transfer ownership of a string. JSON will then free.
- API Stability:
- Internal.
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:
-
json Parsed JSON object returned by jsonParse. nid Base node ID from which to start search for key. Set to zero for the top level. key Property name to add/update. This may include ".". For example: "settings.mode". value Number to update.
- Returns:
- Positive node id if updated successfully. Otherwise a negative error code.
- API Stability:
- Evolving.
Serialize an entire JSON object into a string using a human readable format (JSON_PRETTY).
- Parameters:
-
json Source json.
- Returns:
- Returns a serialized JSON character string. Caller must NOT free.
- API Stability:
- Evolving.
Expand a string template with ${prop.prop...} references.
- Parameters:
-
json Json object. str String template to expand.
- Returns:
- An allocated expanded string. Caller must free.
- API Stability:
- Evolving.
Convert a json value to serialized JSON representation and save in the given buffer.
- Parameters:
-
buf Destination buffer. value Value to convert. flags Json flags.
- API Stability:
- Evolving.
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:
-
json Source json. nid Base node ID from which to convert. Set to zero for the top level. key Property name to serialize below. This may include ".". For example: "settings.mode". flags Serialization 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.
Unlock a json object to allow updates.
- Parameters:
-
json A json object.
- API Stability:
- Evolving.
Typedefs
JSON Node.
- API Stability:
- Evolving.
- Fields:
-
uint allocatedName True if the node text was allocated and must be freed. uint allocatedValue True if the node text was allocated and must be freed. int last Index +1 of last node for which this node is parent. char * name Property name - null terminated. uint type Primitive type of the node (object, array, string or primitive). char * value Property value - null terminated.