C Collections

cjson · Section 3

cjson_get

cjson_get - navigate to a DOM node with a dot-separated path

C Collections (libccollections, -lccollections)

#include <ccollections/cjson.h>
 
cjson cjson_get(cjson root, const char *path);

Walks from root through the components of path and returns the node
that the last component addresses.
 
path is a sequence of components separated by dots.  When the
current node is a CJSON_LIST, a component made of '#' and one or
more decimal digits addresses an array element by its zero-based
index.  In every other case the whole component is a literal object
key, with the '#' as part of the key.  A bare '#' with no digits on
a CJSON_LIST node is an error and the macro returns NULL.
 
A NULL root gives NULL, and a NULL or empty path gives root itself.
An empty component addresses nothing, so the macro gives NULL for
it; a leading dot, a trailing dot and two dots in a row (as in
"a..b") all make an empty component.
 
Escape sequences in path components:
  \.   -> a literal '.' in the key (not treated as a path separator)
  \\   -> a literal '\' in the key
A '\' before any other character is kept as it is.

root   Root cjson node, usually a CJSON_DICTIONARY or a CJSON_LIST.
path   Dot-separated path string, for example
       "users.#0.address.city".

A cjson handle to the target node, which the caller does not own.
NULL when a component along the path is missing, or when the current
node's type doesn't allow the requested step.  A path of 256 bytes or
more is first copied with root's allocator, and the macro also
returns NULL when that copy fails.  A shorter path needs no
allocation.

The returned handle becomes invalid once the caller changes or
destroys the tree.  Do not free it.

cjson city = cjson_get(doc, "users.#0.address.city");
if (cjson_type(city) == CJSON_STRING)
    printf("%s\n", cjson_str_val(city));
 
/* '#0' in an object context is a literal key, not an index */
cjson v = cjson_get(doc, "#0");

cjson_set(3), cjson_type(3)