`JsonArray` is the representation of the array type inside JSON.
A `JsonArray` contains [struct@Json.Node] elements, which may contain
fundamental types, other arrays or objects.
Since arrays can be arbitrarily big, copying them can be expensive; for
this reason, they are reference counted. You can control the lifetime of
a `JsonArray` using [method@Json.Array.ref] and [method@Json.Array.unref].
To append an element, use [method@Json.Array.add_element].
To extract an element at a given index, use [method@Json.Array.get_element].
To retrieve the entire array in list form, use [method@Json.Array.get_elements].
To retrieve the length of the array, use [method@Json.Array.get_length].
Creates a new array.
the newly created array
Creates a new array with `n_elements` slots already allocated.
the newly created array
number of slots to pre-allocate
Conveniently adds an array element into an array.
If `value` is `NULL`, a `null` element will be added instead.
See also: [method@Json.Array.add_element], [method@Json.Node.take_array]
a JSON array
the array to add
Conveniently adds the given boolean value into an array.
See also: [method@Json.Array.add_element], [method@Json.Node.set_boolean]
a JSON array
the boolean value to add
Conveniently adds the given floating point value into an array.
See also: [method@Json.Array.add_element], [method@Json.Node.set_double]
a JSON array
the floating point value to add
Appends the given `node` inside an array.
a JSON array
the element to add
Conveniently adds the given integer value into an array.
See also: [method@Json.Array.add_element], [method@Json.Node.set_int]
a JSON array
the integer value to add
Conveniently adds a `null` element into an array
See also: [method@Json.Array.add_element], `JSON_NODE_NULL`
a JSON array
Conveniently adds an object into an array.
If `value` is `NULL`, a `null` element will be added instead.
See also: [method@Json.Array.add_element], [method@Json.Node.take_object]
a JSON array
the object to add
Conveniently adds the given string value into an array.
See also: [method@Json.Array.add_element], [method@Json.Node.set_string]
a JSON array
the string value to add
Retrieves a copy of the element at the given position in the array.
a copy of the element at the given position
a JSON array
the index of the element to retrieve
Check whether two arrays are equal.
Equality is defined as:
- the array have the same number of elements
- the values of elements in corresponding positions are equal
`TRUE` if the arrays are equal, and `FALSE` otherwise
a JSON array
another JSON array
Iterates over all elements of an array, and calls a function on
each one of them.
It is safe to change the value of an element of the array while
iterating over it, but it is not safe to add or remove elements
from the array.
a JSON array
the function to be called on each element
data to be passed to the function
Conveniently retrieves the array at the given position inside an array.
See also: [method@Json.Array.get_element], [method@Json.Node.get_array]
the array
a JSON array
the index of the element to retrieve
Conveniently retrieves the boolean value of the element at the given
position inside an array.
See also: [method@Json.Array.get_element], [method@Json.Node.get_boolean]
the boolean value
a JSON array
the index of the element to retrieve
Conveniently retrieves the floating point value of the element at
the given position inside an array.
See also: [method@Json.Array.get_element], [method@Json.Node.get_double]
the floating point value
a JSON array
the index of the element to retrieve
Retrieves the element at the given position in the array.
the element at the given position
a JSON array
the index of the element to retrieve
Retrieves all the elements of an array as a list of nodes.
the elements
of the array
a JSON array
Conveniently retrieves the integer value of the element at the given
position inside an array.
See also: [method@Json.Array.get_element], [method@Json.Node.get_int]
the integer value
a JSON array
the index of the element to retrieve
Retrieves the length of the given array
the length of the array
a JSON array
Conveniently checks whether the element at the given position inside the
array contains a `null` value.
See also: [method@Json.Array.get_element], [method@Json.Node.is_null]
`TRUE` if the element is `null`
a JSON array
the index of the element to retrieve
Conveniently retrieves the object at the given position inside an array.
See also: [method@Json.Array.get_element], [method@Json.Node.get_object]
the object
a JSON array
the index of the element to retrieve
Conveniently retrieves the string value of the element at the given
position inside an array.
See also: [method@Json.Array.get_element], [method@Json.Node.get_string]
the string value
a JSON array
the index of the element to retrieve
Calculates a hash value for the given `key`.
The hash is calculated over the array and all its elements, recursively.
If the array is immutable, this is a fast operation; otherwise, it scales
proportionally with the length of the array.
hash value for the key
a JSON array to hash
Check whether the given `array` has been marked as immutable by calling
[method@Json.Array.seal] on it.
%TRUE if the array is immutable
a JSON array
Acquires a reference on the given array.
the passed array, with the reference count
increased by one
the array to reference
Removes the element at the given position inside an array.
This function will release the reference held on the element.
a JSON array
the position of the element to be removed
Seals the given array, making it immutable to further changes.
This function will recursively seal all elements in the array too.
If the `array` is already immutable, this is a no-op.
the array to seal
Releases a reference on the given array.
If the reference count reaches zero, the array is destroyed and all
its allocated resources are freed.
the array to unreference
The function to be passed to [method@Json.Array.foreach_element].
You should not add or remove elements to and from @array within
this function.
It is safe to change the value of @element_node.
the iterated JSON array
the index of the element
the value of the element at the given @index_
data passed to the function
Deserializes the contents of the passed `JsonNode` into a `GBoxed`, for instance:
```c
static gpointer
my_point_deserialize (JsonNode *node)
{
double x = 0.0, y = 0.0;
if (JSON_NODE_HOLDS_ARRAY (node))
{
JsonArray *array = json_node_get_array (node);
if (json_array_get_length (array) == 2)
{
x = json_array_get_double_element (array, 0);
y = json_array_get_double_element (array, 1);
}
}
else if (JSON_NODE_HOLDS_OBJECT (node))
{
JsonObject *obj = json_node_get_object (node);
x = json_object_get_double_member_with_default (obj, "x", 0.0);
y = json_object_get_double_member_with_default (obj, "y", 0.0);
}
// my_point_new() is defined elsewhere
return my_point_new (x, y);
}
```
the newly created boxed structure
a node tree representing a boxed data
Serializes the passed `GBoxed` and stores it inside a `JsonNode`, for instance:
```c
static JsonNode *
my_point_serialize (gconstpointer boxed)
{
const MyPoint *point = boxed;
g_autoptr(JsonBuilder) builder = json_builder_new ();
json_builder_begin_object (builder);
json_builder_set_member_name (builder, "x");
json_builder_add_double_value (builder, point->x);
json_builder_set_member_name (builder, "y");
json_builder_add_double_value (builder, point->y);
json_builder_end_object (builder);
return json_builder_get_root (builder);
}
```
the newly created JSON node tree representing the boxed data
a boxed data structure
`JsonBuilder` provides an object for generating a JSON tree.
The root of the JSON tree can be either a [struct@Json.Object] or a [struct@Json.Array].
Thus the first call must necessarily be either
[method@Json.Builder.begin_object] or [method@Json.Builder.begin_array].
For convenience to language bindings, most `JsonBuilder` method return the
instance, making it easy to chain function calls.
## Using `JsonBuilder`
```c
g_autoptr(JsonBuilder) builder = json_builder_new ();
json_builder_begin_object (builder);
json_builder_set_member_name (builder, "url");
json_builder_add_string_value (builder, "http://www.gnome.org/img/flash/two-thirty.png");
json_builder_set_member_name (builder, "size");
json_builder_begin_array (builder);
json_builder_add_int_value (builder, 652);
json_builder_add_int_value (builder, 242);
json_builder_end_array (builder);
json_builder_end_object (builder);
g_autoptr(JsonNode) root = json_builder_get_root (builder);
g_autoptr(JsonGenerator) gen = json_generator_new ();
json_generator_set_root (gen, root);
g_autofree char *str = json_generator_to_data (gen, NULL);
// str now contains the following JSON data
// { "url" : "http://www.gnome.org/img/flash/two-thirty.png", "size" : [ 652, 242 ] }
```
Creates a new `JsonBuilder`.
You can use this object to generate a JSON tree and obtain the root node.
the newly created builder instance
Creates a new, immutable `JsonBuilder` instance.
It is equivalent to setting the [property@Json.Builder:immutable] property
set to `TRUE` at construction time.
the newly create builder instance
Adds a boolean value to the currently open object member or array.
If called after [method@Json.Builder.set_member_name], sets the given value
as the value of the current member in the open object; otherwise, the value
is appended to the elements of the open array.
See also: [method@Json.Builder.add_value]
the builder instance
a builder
the value of the member or element
Adds a floating point value to the currently open object member or array.
If called after [method@Json.Builder.set_member_name], sets the given value
as the value of the current member in the open object; otherwise, the value
is appended to the elements of the open array.
See also: [method@Json.Builder.add_value]
the builder instance
a builder
the value of the member or element
Adds an integer value to the currently open object member or array.
If called after [method@Json.Builder.set_member_name], sets the given value
as the value of the current member in the open object; otherwise, the value
is appended to the elements of the open array.
See also: [method@Json.Builder.add_value]
the builder instance
a builder
the value of the member or element
Adds a null value to the currently open object member or array.
If called after [method@Json.Builder.set_member_name], sets the given value
as the value of the current member in the open object; otherwise, the value
is appended to the elements of the open array.
See also: [method@Json.Builder.add_value]
the builder instance
a builder
Adds a string value to the currently open object member or array.
If called after [method@Json.Builder.set_member_name], sets the given value
as the value of the current member in the open object; otherwise, the value
is appended to the elements of the open array.
See also: [method@Json.Builder.add_value]
the builder instance
a builder
the value of the member or element
Adds a value to the currently open object member or array.
If called after [method@Json.Builder.set_member_name], sets the given node
as the value of the current member in the open object; otherwise, the node
is appended to the elements of the open array.
The builder will take ownership of the node.
the builder instance
a builder
the value of the member or element
Opens an array inside the given builder.
You can add a new element to the array by using [method@Json.Builder.add_value].
Once you added all elements to the array, you must call
[method@Json.Builder.end_array] to close the array.
the builder instance
a builder
Opens an object inside the given builder.
You can add a new member to the object by using [method@Json.Builder.set_member_name],
followed by [method@Json.Builder.add_value].
Once you added all members to the object, you must call [method@Json.Builder.end_object]
to close the object.
If the builder is in an inconsistent state, this function will return `NULL`.
the builder instance
a builder
Closes the array inside the given builder that was opened by the most
recent call to [method@Json.Builder.begin_array].
This function cannot be called after [method@Json.Builder.set_member_name].
the builder instance
a builder
Closes the object inside the given builder that was opened by the most
recent call to [method@Json.Builder.begin_object].
This function cannot be called after [method@Json.Builder.set_member_name].
the builder instance
a builder
Returns the root of the currently constructed tree.
if the build is incomplete (ie: if there are any opened objects, or any
open object members and array elements) then this function will return
`NULL`.
the root node
a builder
Resets the state of the builder back to its initial state.
a builder
Sets the name of the member in an object.
This function must be followed by of these functions:
- [method@Json.Builder.add_value], to add a scalar value to the member
- [method@Json.Builder.begin_object], to add an object to the member
- [method@Json.Builder.begin_array], to add an array to the member
This function can only be called within an open object.
the builder instance
a builder
the name of the member
Whether the tree should be immutable when created.
Making the output immutable on creation avoids the expense
of traversing it to make it immutable later.
Compile-time version checking. Evaluates to `TRUE` if the version
of JSON-GLib is greater than the required one.
required major version
required minor version
required micro version
Encodes a JSON-GLib version in an hexadecimal number, useful for
integer comparisons.
the major version to encode
the minor version to encode
the micro version to encode
`JsonGenerator` provides an object for generating a JSON data stream
from a tree of [struct@Json.Node] instances, and put it into a buffer
or a file.
Creates a new `JsonGenerator`.
You can use this object to generate a JSON data stream starting from a
data object model composed by [struct@Json.Node]s.
the newly created generator instance
Retrieves the value set using [method@Json.Generator.set_indent].
the number of repetitions per indentation level
a generator
Retrieves the value set using [method@Json.Generator.set_indent_char].
the character to be used when indenting
a generator
Retrieves the value set using [method@Json.Generator.set_pretty].
`TRUE` if the generated JSON should be pretty-printed, and
`FALSE` otherwise
a generator
Retrieves a pointer to the root node set using
[method@Json.Generator.set_root].
the root node
a generator
Sets the number of repetitions for each indentation level.
a generator
the number of repetitions of the indentation character
that should be applied when pretty printing
Sets the character to be used when indenting.
a generator
a Unicode character to be used when indenting
Sets whether the generated JSON should be pretty printed.
Pretty printing will use indentation character specified in the
[property@Json.Generator:indent-char] property and the spacing
specified in the [property@Json.Generator:indent] property.
a generator
whether the generated string should be pretty printed
Sets the root of the JSON data stream to be serialized by
the given generator.
The passed `node` is copied by the generator object, so it can be
safely freed after calling this function.
a generator
the root node
Sets the root of the JSON data stream to be serialized by
the given generator.
The ownership of the passed `node` is transferred to the generator object.
a generator
the root node
Generates a JSON data stream from @generator and returns it as a
buffer.
a newly allocated string holding a JSON data stream
a generator
return location for the length of the returned
buffer
Creates a JSON data stream and puts it inside `filename`, overwriting
the file's current contents.
This operation is atomic, in the sense that the data is written to a
temporary file which is then renamed to the given `filename`.
%TRUE if saving was successful.
a generator
the path to the target file
Generates a JSON data stream and appends it to the string buffer.
the passed string, updated with
the generated JSON data
a generator
a string buffer
Outputs JSON data and writes it (synchronously) to the given stream.
whether the write operation was successful
a generator
the output stream used to write the JSON data
a `GCancellable`
Number of spaces to be used to indent when pretty printing.
The character that should be used when indenting in pretty print.
Whether the output should be "pretty-printed", with indentation and
newlines.
The indentation level can be controlled by using the
[property@Json.Generator:indent] property.
The root node to be used when constructing a JSON data
stream.
Json major version component (e.g. 1 if `JSON_VERSION` is "1.2.3")
Json micro version component (e.g. 3 if `JSON_VERSION` is "1.2.3")
Json minor version component (e.g. 2 if `JSON_VERSION` is "1.2.3")
Evaluates to `TRUE` if the node holds the given type.
the [struct@Json.Node] to check
the desired [enum@Json.NodeType]
Evaluates to `TRUE` if the node holds a JSON array.
the [struct@Json.Node] to check
Evaluates to `TRUE` if the node holds `null`.
the [struct@Json.Node] to check
Evaluates to `TRUE` if the node holds a JSON object.
the [struct@Json.Node] to check
Evaluates to `TRUE` if the node holds a scalar value.
the [struct@Json.Node] to check
Evaluates to the [enum@Json.NodeType] value contained by the node.
the [struct@Json.Node] to check
A generic container of JSON data types.
`JsonNode` can contain fundamental types (integers, booleans, floating point
numbers, strings) and complex types (arrays and objects).
When parsing a JSON data stream you extract the root node and walk
the node tree by retrieving the type of data contained inside the
node with the `JSON_NODE_TYPE` macro. If the node contains a fundamental
type you can retrieve a copy of the `GValue` holding it with the
[method@Json.Node.get_value] function, and then use the `GValue` API to extract
the data; if the node contains a complex type you can retrieve the
[struct@Json.Object] or the [struct@Json.Array] using [method@Json.Node.get_object]
or [method@Json.Node.get_array] respectively, and then retrieve the nodes
they contain.
A `JsonNode` may be marked as immutable using [method@Json.Node.seal]. This
marks the node and all its descendents as read-only, and means that
subsequent calls to setter functions (such as [method@Json.Node.set_array])
on them will abort as a programmer error. By marking a node tree as
immutable, it may be referenced in multiple places and its hash value cached
for fast lookups, without the possibility of a value deep within the tree
changing and affecting hash values. Immutable nodes may be passed to
functions which retain a reference to them without needing to take a copy.
A `JsonNode` supports two types of memory management: `malloc`/`free`
semantics, and reference counting semantics. The two may be mixed to a
limited extent: nodes may be allocated (which gives them a reference count
of 1), referenced one or more times, unreferenced exactly that number of
times (using [method@Json.Node.unref]), then either unreferenced exactly
once more or freed (using [method@Json.Node.free]) to destroy them.
The [method@Json.Node.free] function must not be used when a node might
have a reference count not equal to 1. To this end, JSON-GLib uses
[method@Json.Node.copy] and [method@Json.Node.unref] internally.
Allocates a new, uninitialized node.
Use [method@Json.Node.init] and its variants to initialize the returned value.
the newly allocated node
Creates a new node holding the given @type.
This is a convenience function for [ctor@Json.Node.alloc] and
[method@Json.Node.init], and it's the equivalent of:
```c
json_node_init (json_node_alloc (), type);
```
the newly created node
the type of the node to create
Copies @node.
If the node contains complex data types, their reference
counts are increased, regardless of whether the node is mutable or
immutable.
The copy will be immutable if, and only if, @node is immutable. However,
there should be no need to copy an immutable node.
the copied of the given node
the node to copy
Retrieves the JSON array inside @node.
The reference count of the returned array is increased.
It is a programmer error to call this on a node which doesn’t hold an
array value. Use `JSON_NODE_HOLDS_ARRAY` first.
the JSON array with its reference
count increased.
a node holding an array
Retrieves the object inside @node.
The reference count of the returned object is increased.
It is a programmer error to call this on a node which doesn’t hold an
object value. Use `JSON_NODE_HOLDS_OBJECT` first.
the JSON object
a node holding a JSON object
Gets a copy of the string value stored inside a node.
If the node does not hold a string value, `NULL` is returned.
a copy of the string
inside the node
a node holding a string
Check whether @a and @b are equal node, meaning they have the same
type and same values (checked recursively).
Note that integer values are compared numerically, ignoring type, so a
double value 4.0 is equal to the integer value 4.
`TRUE` if @a and @b are equal; `FALSE` otherwise
a JSON node
another JSON node
Frees the resources allocated by the node.
the node to free
Retrieves the JSON array stored inside a node.
It is a programmer error to call this on a node which doesn’t hold an
array value. Use `JSON_NODE_HOLDS_ARRAY` first.
the JSON array
a node holding an array
Gets the boolean value stored inside a node.
If the node holds an integer or double value which is zero, `FALSE` is
returned; otherwise `TRUE` is returned.
If the node holds a `JSON_NODE_NULL` value or a value of another
non-boolean type, `FALSE` is returned.
a boolean value.
a node holding a boolean value
Gets the double value stored inside a node.
If the node holds an integer value, it is returned as a double.
If the node holds a `FALSE` boolean value, `0.0` is returned; otherwise
a non-zero double is returned.
If the node holds a `JSON_NODE_NULL` value or a value of another
non-double type, `0.0` is returned.
a double value.
a node holding a floating point value
Gets the integer value stored inside a node.
If the node holds a double value, its integer component is returned.
If the node holds a `FALSE` boolean value, `0` is returned; otherwise,
a non-zero integer is returned.
If the node holds a `JSON_NODE_NULL` value or a value of another
non-integer type, `0` is returned.
an integer value.
a node holding an integer
Retrieves the type of a @node.
the type of the node
the node to check
Retrieves the object stored inside a node.
It is a programmer error to call this on a node which doesn’t hold an
object value. Use `JSON_NODE_HOLDS_OBJECT` first.
the JSON object
a node holding a JSON object
Retrieves the parent node of the given @node.
the parent node, or `NULL` if @node
is the root node
the node to query
Gets the string value stored inside a node.
If the node does not hold a string value, `NULL` is returned.
a string value.
a node holding a string
Retrieves a value from a node and copies into @value.
When done using it, call `g_value_unset()` on the `GValue` to free the
associated resources.
It is a programmer error to call this on a node which doesn’t hold a scalar
value. Use `JSON_NODE_HOLDS_VALUE` first.
a node
return location for an uninitialized value
Returns the `GType` of the payload of the node.
For `JSON_NODE_NULL` nodes, the returned type is `G_TYPE_INVALID`.
the type for the payload
the node to check
Calculate a hash value for the given @key.
The hash is calculated over the node and its value, recursively. If the node
is immutable, this is a fast operation; otherwise, it scales proportionally
with the size of the node’s value (for example, with the number of members
in the JSON object if this node contains an object).
hash value for @key
a JSON node to hash
Initializes a @node to a specific @type.
If the node has already been initialized once, it will be reset to
the given type, and any data contained will be cleared.
the initialized node
the node to initialize
the type of JSON node to initialize @node to
Initializes @node to `JSON_NODE_ARRAY` and sets @array into it.
This function will take a reference on @array.
If the node has already been initialized once, it will be reset to
the given type, and any data contained will be cleared.
the initialized node
the node to initialize
the JSON array to initialize @node with, or `NULL`
Initializes @node to `JSON_NODE_VALUE` and sets @value into it.
If the node has already been initialized once, it will be reset to
the given type, and any data contained will be cleared.
the initialized node
the node to initialize
a boolean value
Initializes @node to `JSON_NODE_VALUE` and sets @value into it.
If the node has already been initialized once, it will be reset to
the given type, and any data contained will be cleared.
the initialized node
the node to initialize
a floating point value
Initializes @node to `JSON_NODE_VALUE` and sets @value into it.
If the node has already been initialized once, it will be reset to
the given type, and any data contained will be cleared.
the initialized node
the node to initialize
an integer
Initializes @node to `JSON_NODE_NULL`.
If the node has already been initialized once, it will be reset to
the given type, and any data contained will be cleared.
the initialized node
the node to initialize
Initializes @node to `JSON_NODE_OBJECT` and sets @object into it.
This function will take a reference on @object.
If the node has already been initialized once, it will be reset to
the given type, and any data contained will be cleared.
the initialized node
the node to initialize
the JSON object to initialize @node with, or `NULL`
Initializes @node to `JSON_NODE_VALUE` and sets @value into it.
If the node has already been initialized once, it will be reset to
the given type, and any data contained will be cleared.
the initialized node
the node to initialize
a string value
Check whether the given @node has been marked as immutable by calling
[method@Json.Node.seal] on it.
`TRUE` if the @node is immutable
the node to check
Checks whether @node is a `JSON_NODE_NULL`.
A `JSON_NODE_NULL` node is not the same as a `NULL` node; a `JSON_NODE_NULL`
represents a literal `null` value in the JSON tree.
`TRUE` if the node is null
the node to check
Increments the reference count of @node.
a pointer to @node
the node to reference
Seals the given node, making it immutable to further changes.
In order to be sealed, the @node must have a type and value set. The value
will be recursively sealed — if the node holds an object, that JSON object
will be sealed, etc.
If the `node` is already immutable, this is a no-op.
the node to seal
Sets @array inside @node.
The reference count of @array is increased.
It is a programmer error to call this on a node which doesn’t hold an
array value. Use `JSON_NODE_HOLDS_ARRAY` first.
a node initialized to `JSON_NODE_ARRAY`
a JSON array
Sets @value as the boolean content of the @node, replacing any existing
content.
It is an error to call this on an immutable node, or on a node which is not
a value node.
a node initialized to `JSON_NODE_VALUE`
a boolean value
Sets @value as the double content of the @node, replacing any existing
content.
It is an error to call this on an immutable node, or on a node which is not
a value node.
a node initialized to `JSON_NODE_VALUE`
a double value
Sets @value as the integer content of the @node, replacing any existing
content.
It is an error to call this on an immutable node, or on a node which is not
a value node.
a node initialized to `JSON_NODE_VALUE`
an integer value
Sets @objects inside @node.
The reference count of @object is increased.
If @object is `NULL`, the node’s existing object is cleared.
It is an error to call this on an immutable node, or on a node which is not
an object node.
a node initialized to `JSON_NODE_OBJECT`
a JSON object
Sets the parent node for the given `node`.
It is an error to call this with an immutable @parent.
The @node may be immutable.
the node to change
the parent node
Sets @value as the string content of the @node, replacing any existing
content.
It is an error to call this on an immutable node, or on a node which is not
a value node.
a node initialized to `JSON_NODE_VALUE`
a string value
Sets a scalar value inside the given node.
The contents of the given `GValue` are copied into the `JsonNode`.
The following `GValue` types have a direct mapping to JSON types:
- `G_TYPE_INT64`
- `G_TYPE_DOUBLE`
- `G_TYPE_BOOLEAN`
- `G_TYPE_STRING`
JSON-GLib will also automatically promote the following `GValue` types:
- `G_TYPE_INT` to `G_TYPE_INT64`
- `G_TYPE_FLOAT` to `G_TYPE_DOUBLE`
It is an error to call this on an immutable node, or on a node which is not
a value node.
a node initialized to `JSON_NODE_VALUE`
the value to set
Sets @array inside @node.
The reference count of @array is not increased.
It is a programmer error to call this on a node which doesn’t hold an
array value. Use `JSON_NODE_HOLDS_ARRAY` first.
a node initialized to `JSON_NODE_ARRAY`
a JSON array
Sets @object inside @node.
The reference count of @object is not increased.
It is an error to call this on an immutable node, or on a node which is not
an object node.
a node initialized to `JSON_NODE_OBJECT`
a JSON object
Retrieves the user readable name of the data type contained by @node.
**Note**: The name is only meant for debugging purposes, and there is no
guarantee the name will stay the same across different versions.
a string containing the name of the type
a node
Decrements the reference count of @node.
If the reference count reaches zero, the node is freed.
the node to unreference
Indicates the content of a node.
The node contains a JSON object
The node contains a JSON array
The node contains a fundamental type
Special type, for nodes containing null
`JsonObject` is the representation of the object type inside JSON.
A `JsonObject` contains [struct@Json.Node] "members", which may contain
fundamental types, arrays or other objects; each member of an object is
accessed using a unique string, or "name".
Since objects can be arbitrarily big, copying them can be expensive; for
this reason they are reference counted. You can control the lifetime of
a `JsonObject` using [method@Json.Object.ref] and [method@Json.Object.unref].
To add or overwrite a member with a given name, use [method@Json.Object.set_member].
To extract a member with a given name, use [method@Json.Object.get_member].
To retrieve the list of members, use [method@Json.Object.get_members].
To retrieve the size of the object (that is, the number of members it has),
use [method@Json.Object.get_size].
Creates a new object.
the newly created object
Adds a new member for the given name and value into an object.
This function will return if the object already contains a member
with the same name.
Use [method@Json.Object.set_member] instead
a JSON object
the name of the member
the value of the member
Retrieves a copy of the value of the given member inside an object.
a copy of the value for the
requested object member
a JSON object
the name of the JSON object member to access
Check whether @a and @b are equal objects, meaning they have the same
set of members, and the values of corresponding members are equal.
`TRUE` if @a and @b are equal, and `FALSE` otherwise
a JSON object
another JSON object
Iterates over all members of @object and calls @func on
each one of them.
It is safe to change the value of a member of the oobject
from within the iterator function, but it is not safe to add or
remove members from the object.
The order in which the object members are iterated is the
insertion order.
a JSON object
the function to be called on each member
data to be passed to the function
Convenience function that retrieves the array
stored in @member_name of @object. It is an error to specify a
@member_name which does not exist.
If @member_name contains `null`, then this function will return `NULL`.
See also: [method@Json.Object.get_member], [method@Json.Object.has_member]
the array inside the object's member
a JSON object
the name of the member
Convenience function that retrieves the boolean value
stored in @member_name of @object. It is an error to specify a
@member_name which does not exist.
See also: [method@Json.Object.get_boolean_member_with_default],
[method@Json.Object.get_member], [method@Json.Object.has_member]
the boolean value of the object's member
a JSON object
the name of the member
Convenience function that retrieves the boolean value
stored in @member_name of @object.
If @member_name does not exist, does not contain a scalar value,
or contains `null`, then @default_value is returned instead.
the boolean value of the object's member, or the
given default
a JSON object
the name of the @object member
the value to return if @member_name is not valid
Convenience function that retrieves the floating point value
stored in @member_name of @object. It is an error to specify a
@member_name which does not exist.
See also: [method@Json.Object.get_double_member_with_default],
[method@Json.Object.get_member], [method@Json.Object.has_member]
the floating point value of the object's member
a JSON object
the name of the member
Convenience function that retrieves the floating point value
stored in @member_name of @object.
If @member_name does not exist, does not contain a scalar value,
or contains `null`, then @default_value is returned instead.
the floating point value of the object's member, or the
given default
a JSON object
the name of the @object member
the value to return if @member_name is not valid
Convenience function that retrieves the integer value
stored in @member_name of @object. It is an error to specify a
@member_name which does not exist.
See also: [method@Json.Object.get_int_member_with_default],
[method@Json.Object.get_member], [method@Json.Object.has_member]
the integer value of the object's member
a JSON object
the name of the object member
Convenience function that retrieves the integer value
stored in @member_name of @object.
If @member_name does not exist, does not contain a scalar value,
or contains `null`, then @default_value is returned instead.
the integer value of the object's member, or the
given default
a JSON object
the name of the object member
the value to return if @member_name is not valid
Retrieves the value of the given member inside an object.
the value for the
requested object member
a JSON object
the name of the JSON object member to access
Retrieves all the names of the members of an object.
You can obtain the value for each member by iterating the returned list
and calling [method@Json.Object.get_member].
the
member names of the object
a JSON object
Convenience function that checks whether the value
stored in @member_name of @object is null. It is an error to
specify a @member_name which does not exist.
See also: [method@Json.Object.get_member], [method@Json.Object.has_member]
`TRUE` if the value is `null`
a JSON object
the name of the member
Convenience function that retrieves the object
stored in @member_name of @object. It is an error to specify a @member_name
which does not exist.
If @member_name contains `null`, then this function will return `NULL`.
See also: [method@Json.Object.get_member], [method@Json.Object.has_member]
the object inside the object's member
a JSON object
the name of the member
Retrieves the number of members of a JSON object.
the number of members
a JSON object
Convenience function that retrieves the string value
stored in @member_name of @object. It is an error to specify a
@member_name that does not exist.
See also: [method@Json.Object.get_string_member_with_default],
[method@Json.Object.get_member], [method@Json.Object.has_member]
the string value of the object's member
a JSON object
the name of the member
Convenience function that retrieves the string value
stored in @member_name of @object.
If @member_name does not exist, does not contain a scalar value,
or contains `null`, then @default_value is returned instead.
the string value of the object's member, or the
given default
a JSON object
the name of the @object member
the value to return if @member_name is not valid
Retrieves all the values of the members of an object.
the
member values of the object
a JSON object
Checks whether @object has a member named @member_name.
`TRUE` if the JSON object has the requested member
a JSON object
the name of a JSON object member
Calculate a hash value for the given @key (a JSON object).
The hash is calculated over the object and all its members, recursively. If
the object is immutable, this is a fast operation; otherwise, it scales
proportionally with the number of members in the object.
hash value for @key
a JSON object to hash
Checks whether the given object has been marked as immutable by calling
[method@Json.Object.seal] on it.
`TRUE` if the object is immutable
a JSON object
Acquires a reference on the given object.
the given object, with the reference count
increased by one.
a JSON object
Removes @member_name from @object, freeing its allocated resources.
a JSON object
the name of the member to remove
Seals the object, making it immutable to further changes.
This function will recursively seal all members of the object too.
If the object is already immutable, this is a no-op.
a JSON object
Convenience function for setting an object member with an array value.
See also: [method@Json.Object.set_member], [method@Json.Node.take_array]
a JSON object
the name of the member
the value of the member
Convenience function for setting an object member with a boolean value.
See also: [method@Json.Object.set_member], [method@Json.Node.init_boolean]
a JSON object
the name of the member
the value of the member
Convenience function for setting an object member with a floating point value.
See also: [method@Json.Object.set_member], [method@Json.Node.init_double]
a JSON object
the name of the member
the value of the member
Convenience function for setting an object member with an integer value.
See also: [method@Json.Object.set_member], [method@Json.Node.init_int]
a JSON object
the name of the member
the value of the member
Sets the value of a member inside an object.
If the object does not have a member with the given name, a new member
is created.
If the object already has a member with the given name, the current
value is overwritten with the new.
a JSON object
the name of the member
the value of the member
Convenience function for setting an object member with a `null` value.
See also: [method@Json.Object.set_member], [method@Json.Node.init_null]
a JSON object
the name of the member
Convenience function for setting an object member with an object value.
See also: [method@Json.Object.set_member], [method@Json.Node.take_object]
a JSON object
the name of the member
the value of the member
Convenience function for setting an object member with a string value.
See also: [method@Json.Object.set_member], [method@Json.Node.init_string]
a JSON object
the name of the member
the value of the member
Releases a reference on the given object.
If the reference count reaches zero, the object is destroyed and
all its resources are freed.
a JSON object
The function to be passed to [method@Json.Object.foreach_member].
You should not add or remove members to and from @object within
this function.
It is safe to change the value of @member_node.
the iterated JSON object
the name of the member
the value of the member
data passed to the function
An iterator object used to iterate over the members of a JSON object.
`JsonObjectIter` must be allocated on the stack and initialised using
[method@Json.ObjectIter.init] or [method@Json.ObjectIter.init_ordered].
The iterator is invalidated if the object is modified during
iteration.
All the fields in the `JsonObjectIter` structure are private and should
never be accessed directly.
Initialises the @iter and associate it with @object.
```c
JsonObjectIter iter;
const gchar *member_name;
JsonNode *member_node;
json_object_iter_init (&iter, some_object);
while (json_object_iter_next (&iter, &member_name, &member_node))
{
// Do something with @member_name and @member_node.
}
```
The iterator initialized with this function will iterate the
members of the object in an undefined order.
See also: [method@Json.ObjectIter.init_ordered]
an uninitialised JSON object iterator
the JSON object to iterate over
Initialises the @iter and associate it with @object.
```c
JsonObjectIter iter;
const gchar *member_name;
JsonNode *member_node;
json_object_iter_init_ordered (&iter, some_object);
while (json_object_iter_next_ordered (&iter, &member_name, &member_node))
{
// Do something with @member_name and @member_node.
}
```
See also: [method@Json.ObjectIter.init]
an uninitialised iterator
the JSON object to iterate over
Advances the iterator and retrieves the next member in the object.
If the end of the object is reached, `FALSE` is returned and @member_name
and @member_node are set to invalid values. After that point, the @iter
is invalid.
The order in which members are returned by the iterator is undefined. The
iterator is invalidated if the object is modified during iteration.
You must use this function with an iterator initialized with
[method@Json.ObjectIter.init]; using this function with an iterator
initialized with [method@Json.ObjectIter.init_ordered] yields undefined
behavior.
See also: [method@Json.ObjectIter.next_ordered]
`TRUE` if @member_name and @member_node are valid; `FALSE` if
there are no more members
a JSON object iterator
return
location for the member name, or %NULL to ignore
return
location for the member value, or %NULL to ignore
Advances the iterator and retrieves the next member in the object.
If the end of the object is reached, `FALSE` is returned and @member_name and
@member_node are set to invalid values. After that point, the @iter is invalid.
The order in which members are returned by the iterator is the same order in
which the members were added to the `JsonObject`. The iterator is invalidated
if its `JsonObject` is modified during iteration.
You must use this function with an iterator initialized with
[method@Json.ObjectIter.init_ordered]; using this function with an iterator
initialized with [method@Json.ObjectIter.init] yields undefined behavior.
See also: [method@Json.ObjectIter.next]
`TRUE `if @member_name and @member_node are valid; `FALSE` if the end
of the object has been reached
an ordered JSON object iterator
return
location for the member name, or %NULL to ignore
return
location for the member value, or %NULL to ignore
The maximum recursion depth for a JSON tree.
`JsonParser` provides an object for parsing a JSON data stream, either
inside a file or inside a static buffer.
## Using `JsonParser`
The `JsonParser` API is fairly simple:
```c
gboolean
parse_json (const char *filename)
{
g_autoptr(JsonParser) parser = json_parser_new ();
g_autoptr(GError) error = NULL
json_parser_load_from_file (parser, filename, &error);
if (error != NULL)
{
g_critical ("Unable to parse '%s': %s", filename, error->message);
return FALSE;
}
g_autoptr(JsonNode) root = json_parser_get_root (parser);
// manipulate the object tree from the root node
return TRUE
}
```
By default, the entire process of loading the data and parsing it is
synchronous; the [method@Json.Parser.load_from_stream_async] API will
load the data asynchronously, but parse it in the main context as the
signals of the parser must be emitted in the same thread. If you do
not use signals, and you wish to also parse the JSON data without blocking,
you should use a `GTask` and the synchronous `JsonParser` API inside the
task itself.
Creates a new JSON parser.
You can use the `JsonParser` to load a JSON stream from either a file or a
buffer and then walk the hierarchy using the data types API.
the newly created parser
Creates a new parser instance with its [property@Json.Parser:immutable]
property set to `TRUE` to create immutable output trees.
the newly created parser
class handler for the JsonParser::array-element signal
class handler for the JsonParser::array-end signal
class handler for the JsonParser::array-start signal
class handler for the JsonParser::error signal
class handler for the JsonParser::object-end signal
class handler for the JsonParser::object-member signal
class handler for the JsonParser::object-start signal
class handler for the JsonParser::parse-end signal
class handler for the JsonParser::parse-start signal
Retrieves the line currently parsed, starting from 1.
This function has defined behaviour only while parsing; calling this
function from outside the signal handlers emitted by the parser will
yield 0.
the currently parsed line, or 0.
a parser
Retrieves the current position inside the current line, starting
from 0.
This function has defined behaviour only while parsing; calling this
function from outside the signal handlers emitted by the parser will
yield 0.
the position in the current line, or 0.
a parser
Retrieves the top level node from the parsed JSON stream.
If the parser input was an empty string, or if parsing failed, the root
will be `NULL`. It will also be `NULL` if it has been stolen using
[method@Json.Parser.steal_root].
the root node.
a parser
Retrieves whether the parser is operating in strict mode.
true if the parser is strict, and false otherwise
the JSON parser
A JSON data stream might sometimes contain an assignment, like:
```
var _json_data = { "member_name" : [ ...
```
even though it would technically constitute a violation of the RFC.
`JsonParser` will ignore the left hand identifier and parse the right
hand value of the assignment. `JsonParser` will record, though, the
existence of the assignment in the data stream and the variable name
used.
`TRUE` if there was an assignment, and `FALSE` otherwise
a parser
the variable name
Loads a JSON stream from a buffer and parses it.
You can call this function multiple times with the same parser, but the
contents of the parser will be destroyed each time.
`TRUE` if the buffer was succesfully parsed
a parser
the buffer to parse
the length of the buffer, or -1 if it is `NUL` terminated
Loads a JSON stream from the content of `filename` and parses it.
If the file is large or shared between processes,
[method@Json.Parser.load_from_mapped_file] may be a more efficient
way to load it.
See also: [method@Json.Parser.load_from_data]
`TRUE` if the file was successfully loaded and parsed.
a parser
the path for the file to parse
Loads a JSON stream from the content of `filename` and parses it.
Unlike [method@Json.Parser.load_from_file], `filename` will be memory
mapped as read-only and parsed. `filename` will be unmapped before this
function returns.
If mapping or reading the file fails, a `G_FILE_ERROR` will be returned.
`TRUE` if the file was successfully loaded and parsed.
a parser
the path for the file to parse
Loads the contents of an input stream and parses them.
If `cancellable` is not `NULL`, then the operation can be cancelled by
triggering the cancellable object from another thread. If the
operation was cancelled, `G_IO_ERROR_CANCELLED` will be set
on the given `error`.
`TRUE` if the data stream was successfully read and
parsed, and `FALSE` otherwise
a parser
the input stream with the JSON data
a #GCancellable
Asynchronously reads the contents of a stream.
For more details, see [method@Json.Parser.load_from_stream], which is the
synchronous version of this call.
When the operation is finished, @callback will be called. You should
then call [method@Json.Parser.load_from_stream_finish] to get the result
of the operation.
a parser
the input stream with the JSON data
a #GCancellable
the function to call when the request is satisfied
the data to pass to @callback
Finishes an asynchronous stream loading started with
[method@Json.Parser.load_from_stream_async].
`TRUE` if the content of the stream was successfully retrieved
and parsed, and `FALSE` otherwise
a parser
the result of the asynchronous operation
Sets whether the parser should operate in strict mode.
If @strict is true, `JsonParser` will strictly conform to
the JSON format.
If @strict is false, `JsonParser` will allow custom extensions
to the JSON format, like comments.
the JSON parser
whether the parser should be strict
Steals the top level node from the parsed JSON stream.
This will be `NULL` in the same situations as [method@Json.Parser.get_root]
return `NULL`.
the root node
a parser
Whether the tree built by the parser should be immutable
when created.
Making the output immutable on creation avoids the expense
of traversing it to make it immutable later.
Whether the parser should be strictly conforming to the
JSON format, or allow custom extensions like comments.
The `::array-element` signal is emitted each time a parser
has successfully parsed a single element of a JSON array.
Derive your own parser type from `JsonParser` and
override the [vfunc@Json.Parser.array_element] virtual function
a JSON array
the index of the newly parsed array element
The `::array-end` signal is emitted each time a parser
has successfully parsed an entire JSON array.
Derive your own parser type from `JsonParser` and
override the [vfunc@Json.Parser.array_end] virtual function
the parsed JSON array
The `::array-start` signal is emitted each time a parser
starts parsing a JSON array.
Derive your own parser type from `JsonParser` and
override the [vfunc@Json.Parser.array_start] virtual function
The `::error` signal is emitted each time a parser encounters
an error in a JSON stream.
Derive your own parser type from `JsonParser` and
override the [vfunc@Json.Parser.error] virtual function
the error
The `::object-end` signal is emitted each time a parser
has successfully parsed an entire JSON object.
Derive your own parser type from `JsonParser` and
override the [vfunc@Json.Parser.object_end] virtual function
the parsed JSON object
The `::object-member` signal is emitted each time a parser
has successfully parsed a single member of a JSON object.
Derive your own parser type from `JsonParser` and
override the [vfunc@Json.Parser.object_member] virtual function
the JSON object being parsed
the name of the newly parsed member
This signal is emitted each time a parser starts parsing a JSON object.
Derive your own parser type from `JsonParser` and
override the [vfunc@Json.Parser.object_start] virtual function
This signal is emitted when a parser successfully finished parsing a
JSON data stream.
Derive your own parser type from `JsonParser` and
override the [vfunc@Json.Parser.parse_end] virtual function
This signal is emitted when a parser starts parsing a JSON data stream.
Derive your own parser type from `JsonParser` and
override the [vfunc@Json.Parser.parse_start] virtual function
The class structure for the JsonParser type.
class handler for the JsonParser::parse-start signal
class handler for the JsonParser::object-start signal
class handler for the JsonParser::object-member signal
class handler for the JsonParser::object-end signal
class handler for the JsonParser::array-start signal
class handler for the JsonParser::array-element signal
class handler for the JsonParser::array-end signal
class handler for the JsonParser::parse-end signal
class handler for the JsonParser::error signal
Error codes for `JSON_PARSER_ERROR`.
This enumeration can be extended at later date
parse error
unexpected trailing comma
expected comma
expected colon
invalid bareword
Empty member name.
Invalid data.
unknown error
Too many levels of nesting.
Invalid structure.
Invalid assignment.
`JsonPath` is a simple class implementing the JSONPath syntax for extracting
data out of a JSON tree.
While the semantics of the JSONPath expressions are heavily borrowed by the
XPath specification for XML, the syntax follows the ECMAScript origins of
JSON.
Once a `JsonPath` instance has been created, it has to compile a JSONPath
expression using [method@Json.Path.compile] before being able to match it to
a JSON tree; the same `JsonPath` instance can be used to match multiple JSON
trees. It it also possible to compile a new JSONPath expression using the
same `JsonPath` instance; the previous expression will be discarded only if
the compilation of the new expression is successful.
The simple convenience function [func@Json.Path.query] can be used for
one-off matching.
## Syntax of the JSONPath expressions
A JSONPath expression is composed by path indices and operators.
Each path index can either be a member name or an element index inside
a JSON tree. A JSONPath expression must start with the `$` operator; each
path index is separated using either the dot notation or the bracket
notation, e.g.:
```
// dot notation
$.store.book[0].title
// bracket notation
$['store']['book'][0]['title']
```
The available operators are:
* The `$` character represents the root node of the JSON tree, and
matches the entire document.
* Child nodes can either be matched using `.` or `[]`. For instance,
both `$.store.book` and `$['store']['book']` match the contents of
the book member of the store object.
* Child nodes can be reached without specifying the whole tree structure
through the recursive descent operator, or `..`. For instance,
`$..author` matches all author member in every object.
* Child nodes can grouped through the wildcard operator, or `*`. For
instance, `$.store.book[*].author` matches all author members of any
object element contained in the book array of the store object.
* Element nodes can be accessed using their index (starting from zero)
in the subscript operator `[]`. For instance, `$.store.book[0]` matches
the first element of the book array of the store object.
* Subsets of element nodes can be accessed using the set notation
operator `[i,j,...]`. For instance, `$.store.book[0,2]` matches the
elements 0 and 2 (the first and third) of the book array of the store
object.
* Slices of element nodes can be accessed using the slice notation
operation `[start:end:step]`. If start is omitted, the starting index
of the slice is implied to be zero; if end is omitted, the ending index
of the slice is implied to be the length of the array; if step is
omitted, the step of the slice is implied to be 1. For instance,
`$.store.book[:2]` matches the first two elements of the book array
of the store object.
More information about JSONPath is available on Stefan Gössner's
[JSONPath website](http://goessner.net/articles/JsonPath/).
## Example of JSONPath matches
The following example shows some of the results of using `JsonPath`
on a JSON tree. We use the following JSON description of a bookstore:
```json
{ "store": {
"book": [
{ "category": "reference", "author": "Nigel Rees",
"title": "Sayings of the Century", "price": "8.95" },
{ "category": "fiction", "author": "Evelyn Waugh",
"title": "Sword of Honour", "price": "12.99" },
{ "category": "fiction", "author": "Herman Melville",
"title": "Moby Dick", "isbn": "0-553-21311-3",
"price": "8.99" },
{ "category": "fiction", "author": "J. R. R. Tolkien",
"title": "The Lord of the Rings", "isbn": "0-395-19395-8",
"price": "22.99" }
],
"bicycle": { "color": "red", "price": "19.95" }
}
}
```
We can parse the JSON using [class@Json.Parser]:
```c
JsonParser *parser = json_parser_new ();
json_parser_load_from_data (parser, json_data, -1, NULL);
```
If we run the following code:
```c
JsonNode *result;
JsonPath *path = json_path_new ();
json_path_compile (path, "$.store..author", NULL);
result = json_path_match (path, json_parser_get_root (parser));
```
The `result` node will contain an array with all values of the
author member of the objects in the JSON tree. If we use a
[class@Json.Generator] to convert the `result` node to a string
and print it:
```c
JsonGenerator *generator = json_generator_new ();
json_generator_set_root (generator, result);
char *str = json_generator_to_data (generator, NULL);
g_print ("Results: %s\n", str);
```
The output will be:
```json
["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]
```
Creates a new `JsonPath` instance.
Once created, the `JsonPath` object should be used with
[method@Json.Path.compile] and [method@Json.Path.match].
the newly created path
Queries a JSON tree using a JSONPath expression.
This function is a simple wrapper around [ctor@Json.Path.new],
[method@Json.Path.compile], and [method@Json.Path.match]. It implicitly
creates a `JsonPath` instance, compiles the given expression and matches
it against the JSON tree pointed by `root`.
a newly-created node of type
`JSON_NODE_ARRAY` containing the array of matching nodes
a JSONPath expression
the root of a JSON tree
Validates and decomposes the given expression.
A JSONPath expression must be compiled before calling
[method@Json.Path.match].
`TRUE` if the compilation was successful, and `FALSE`
otherwise
a path
a JSONPath expression
Matches the JSON tree pointed by `root` using the expression compiled
into the `JsonPath`.
The nodes matching the expression will be copied into an array.
a newly-created node of type
`JSON_NODE_ARRAY` containing the array of matching nodes
a compiled path
the root node of the JSON data to match
Error codes for `JSON_PATH_ERROR`.
This enumeration can be extended at later date
Invalid query
`JsonReader` provides a simple, cursor-based API for parsing a JSON DOM.
It is similar, in spirit, to the XML Reader API.
The cursor is moved by the `json_reader_read_*` and the `json_reader_end_*`
functions. You can enter a JSON object using [method@Json.Reader.read_member]
with the name of the object member, access the value at that position, and
move the cursor back one level using [method@Json.Reader.end_member]; arrays
work in a similar way, using [method@Json.Reader.read_element] with the
index of the element, and using [method@Json.Reader.end_element] to move
the cursor back.
## Using `JsonReader`
```c
g_autoptr(JsonParser) parser = json_parser_new ();
// str is defined elsewhere and contains:
// { "url" : "http://www.gnome.org/img/flash/two-thirty.png", "size" : [ 652, 242 ] }
json_parser_load_from_data (parser, str, -1, NULL);
g_autoptr(JsonReader) reader = json_reader_new (json_parser_get_root (parser));
// Enter the "url" member of the object
json_reader_read_member (reader, "url");
const char *url = json_reader_get_string_value (reader);
// url now contains "http://www.gnome.org/img/flash/two-thirty.png"
json_reader_end_member (reader);
// Enter the "size" member of the object
json_reader_read_member (reader, "size");
// Enter the first element of the array
json_reader_read_element (reader, 0);
int width = json_reader_get_int_value (reader);
// width now contains 652
json_reader_end_element (reader);
// Enter the second element of the array
json_reader_read_element (reader, 1);
int height = json_reader_get_int_value (reader);
// height now contains 242
json_reader_end_element (reader);
json_reader_end_member (reader);
```
## Error handling
In case of error, `JsonReader` will be set in an error state; all subsequent
calls will simply be ignored until a function that resets the error state is
called, e.g.:
```c
// ask for the 7th element; if the element does not exist, the
// reader will be put in an error state
json_reader_read_element (reader, 6);
// in case of error, this will return NULL, otherwise it will
// return the value of the element
str = json_reader_get_string_value (value);
// this function resets the error state if any was set
json_reader_end_element (reader);
```
If you want to detect the error state as soon as possible, you can use
[method@Json.Reader.get_error]:
```c
// like the example above, but in this case we print out the
// error immediately
if (!json_reader_read_element (reader, 6))
{
const GError *error = json_reader_get_error (reader);
g_print ("Unable to read the element: %s", error->message);
}
```
Creates a new reader.
You can use this object to read the contents of the JSON tree starting
from the given node.
the newly created reader
the root node
Counts the elements of the current position, if the reader is
positioned on an array.
In case of failure, the reader is set to an error state.
the number of elements, or -1.
a reader
Counts the members of the current position, if the reader is
positioned on an object.
In case of failure, the reader is set to an error state.
the number of members, or -1
a reader
Moves the cursor back to the previous node after being positioned
inside an array.
This function resets the error state of the reader, if any was set.
a reader
Moves the cursor back to the previous node after being positioned
inside an object.
This function resets the error state of the reader, if any was set.
a reader
Retrieves the boolean value of the current position of the reader.
See also: [method@Json.Reader.get_value]
the boolean value
a reader
Retrieves the reader node at the current position.
the current node of the reader
a reader
Retrieves the floating point value of the current position of the reader.
See also: [method@Json.Reader.get_value]
the floating point value
a reader
Retrieves the error currently set on the reader.
the current error
a reader
Retrieves the integer value of the current position of the reader.
See also: [method@Json.Reader.get_value]
the integer value
a reader
Retrieves the name of the current member.
In case of failure, the reader is set to an error state.
the name of the member
a reader
Checks whether the value of the current position of the reader is `null`.
See also: [method@Json.Reader.get_value]
`TRUE` if `null` is set, and `FALSE` otherwise
a reader
Retrieves the string value of the current position of the reader.
See also: [method@Json.Reader.get_value]
the string value
a reader
Retrieves the value node at the current position of the reader.
If the current position does not contain a scalar value, the reader
is set to an error state.
the current value node
a reader
Checks whether the reader is currently on an array.
`TRUE` if the reader is on an array
a reader
Checks whether the reader is currently on an object.
`TRUE` if the reader is on an object
a reader
Checks whether the reader is currently on a value.
`TRUE` if the reader is on a value
a reader
Retrieves a list of member names from the current position, if the reader
is positioned on an object.
In case of failure, the reader is set to an error state.
the members of
the object
a reader
Advances the cursor of the reader to the element of the array or
the member of the object at the given position.
You can use [method@Json.Reader.get_value] and its wrapper functions to
retrieve the value of the element; for instance, the following code will
read the first element of the array at the current cursor position:
```c
json_reader_read_element (reader, 0);
int_value = json_reader_get_int_value (reader);
```
After reading the value, you should call [method@Json.Reader.end_element]
to reposition the cursor inside the reader, e.g.:
```c
const char *str_value = NULL;
json_reader_read_element (reader, 1);
str_value = json_reader_get_string_value (reader);
json_reader_end_element (reader);
json_reader_read_element (reader, 2);
str_value = json_reader_get_string_value (reader);
json_reader_end_element (reader);
```
If the reader is not currently on an array or an object, or if the index is
bigger than the size of the array or the object, the reader will be
put in an error state until [method@Json.Reader.end_element] is called. This
means that, if used conditionally, [method@Json.Reader.end_element] must be
called on all branches:
```c
if (!json_reader_read_element (reader, 1))
{
g_propagate_error (error, json_reader_get_error (reader));
json_reader_end_element (reader);
return FALSE;
}
else
{
const char *str_value = json_reader_get_string_value (reader);
json_reader_end_element (reader);
// use str_value
return TRUE;
}
```c
`TRUE` on success, and `FALSE` otherwise
a reader
the index of the element
Advances the cursor of the reader to the `member_name` of the object at
the current position.
You can use [method@Json.Reader.get_value] and its wrapper functions to
retrieve the value of the member; for instance:
```c
json_reader_read_member (reader, "width");
width = json_reader_get_int_value (reader);
```
After reading the value, `json_reader_end_member()` should be called to
reposition the cursor inside the reader, e.g.:
```c
json_reader_read_member (reader, "author");
author = json_reader_get_string_value (reader);
json_reader_end_member (reader);
json_reader_read_member (reader, "title");
title = json_reader_get_string_value (reader);
json_reader_end_member (reader);
```
If the reader is not currently on an object, or if the `member_name` is not
defined in the object, the reader will be put in an error state until
[method@Json.Reader.end_member] is called. This means that if used
conditionally, [method@Json.Reader.end_member] must be called on all branches:
```c
if (!json_reader_read_member (reader, "title"))
{
g_propagate_error (error, json_reader_get_error (reader));
json_reader_end_member (reader);
return FALSE;
}
else
{
const char *str_value = json_reader_get_string_value (reader);
json_reader_end_member (reader);
// use str_value
return TRUE;
}
```
`TRUE` on success, and `FALSE` otherwise
a reader
the name of the member to read
Sets the root node of the JSON tree to be read by @reader.
The reader will take a copy of the node.
a reader
the root node
The root of the JSON tree that the reader should read.
Error codes for `JSON_READER_ERROR`.
This enumeration can be extended at later date
No array found at the current position
Index out of bounds
No object found at the current position
Member not found
No valid node found at the current position
The node at the current position does not
hold a value
The node at the current position does not
hold a value of the desired type
`JsonSerializable` is an interface for controlling the serialization
and deserialization of `GObject` classes.
Implementing this interface allows controlling how the class is going
to be serialized or deserialized by [func@Json.construct_gobject] and
[func@Json.serialize_gobject], respectively.
Asks a `JsonSerializable` implementation to deserialize the
property contained inside `property_node` and place its value
into `value`.
The `value` can be:
- an empty `GValue` initialized by `G_VALUE_INIT`, which will be automatically
initialized with the expected type of the property by using the given
property description (since JSON-GLib 1.6)
- a `GValue` initialized with the expected type of the property
This function will not be called for properties that are marked as
as `G_PARAM_CONSTRUCT_ONLY`.
`TRUE` if the property was successfully deserialized
a serializable object
the name of the property to serialize
a pointer to an uninitialized value
a property description
the JSON node containing the serialized property
Calls the [vfunc@Json.Serializable.find_property] implementation on
the `JsonSerializable` instance, which will return the property
description for the given name.
the property description
a serializable object
the name of the property
Calls the [vfunc@Json.Serializable.get_property] implementation
on the `JsonSerializable` instance, which will get the value of
the given property.
a serializable object
a property description
return location for the property value
virtual function for listing the installed property
definitions
Asks a `JsonSerializable` implementation to serialize an object
property into a JSON node.
a node containing the serialized property
a serializable object
the name of the property to serialize
the value of the property to serialize
a property description
Calls the [vfunc@Json.Serializable.set_property] implementation
on the `JsonSerializable` instance, which will set the property
with the given value.
a serializable object
a property description
the property value to set
Calls the default implementation of the [vfunc@Json.Serializable.deserialize_property]
virtual function.
This function can be used inside a custom implementation of the
`deserialize_property()` virtual function in lieu of calling the
default implementation through `g_type_default_interface_peek()`:
```c
JsonSerializable *iface;
gboolean res;
iface = g_type_default_interface_peek (JSON_TYPE_SERIALIZABLE);
res = iface->deserialize_property (serializable, property_name,
value,
pspec,
property_node);
```
`TRUE` if the property was successfully deserialized
a serializable object
the name of the property to deserialize
a pointer to an uninitialized value
a property description
the JSON node containing the serialized property
Calls the default implementation of the [vfunc@Json.Serializable.serialize_property]
virtual function.
This function can be used inside a custom implementation of the
`serialize_property()` virtual function in lieu of calling the
default implementation through `g_type_default_interface_peek()`:
```c
JsonSerializable *iface;
JsonNode *node;
iface = g_type_default_interface_peek (JSON_TYPE_SERIALIZABLE);
node = iface->serialize_property (serializable, property_name,
value,
pspec);
```
This function will return `NULL` if the property could not be
serialized.
a node containing the
serialized property
a serializable object
the name of the property to serialize
the value of the property to serialize
a property description
Asks a `JsonSerializable` implementation to deserialize the
property contained inside `property_node` and place its value
into `value`.
The `value` can be:
- an empty `GValue` initialized by `G_VALUE_INIT`, which will be automatically
initialized with the expected type of the property by using the given
property description (since JSON-GLib 1.6)
- a `GValue` initialized with the expected type of the property
This function will not be called for properties that are marked as
as `G_PARAM_CONSTRUCT_ONLY`.
`TRUE` if the property was successfully deserialized
a serializable object
the name of the property to serialize
a pointer to an uninitialized value
a property description
the JSON node containing the serialized property
Calls the [vfunc@Json.Serializable.find_property] implementation on
the `JsonSerializable` instance, which will return the property
description for the given name.
the property description
a serializable object
the name of the property
Calls the [vfunc@Json.Serializable.get_property] implementation
on the `JsonSerializable` instance, which will get the value of
the given property.
a serializable object
a property description
return location for the property value
Calls the [vfunc@Json.Serializable.list_properties] implementation on
the `JsonSerializable` instance, which will return the list of serializable
properties.
the serializable
properties of the object
a serializable object
return location for the length of the returned array
Asks a `JsonSerializable` implementation to serialize an object
property into a JSON node.
a node containing the serialized property
a serializable object
the name of the property to serialize
the value of the property to serialize
a property description
Calls the [vfunc@Json.Serializable.set_property] implementation
on the `JsonSerializable` instance, which will set the property
with the given value.
a serializable object
a property description
the property value to set
Interface that allows serializing and deserializing object instances
with properties storing complex data types.
The [func@Json.gobject_from_data] and [func@Json.gobject_to_data]
functions will check if the passed object type implements this interface,
so it can also be used to override the default property serialization
sequence.
virtual function for serializing an object property
into JSON
a node containing the serialized property
a serializable object
the name of the property to serialize
the value of the property to serialize
a property description
virtual function for deserializing JSON
into an object property
`TRUE` if the property was successfully deserialized
a serializable object
the name of the property to serialize
a pointer to an uninitialized value
a property description
the JSON node containing the serialized property
virtual function for finding a property definition using
its name
the property description
a serializable object
the name of the property
virtual function for listing the installed property
definitions
virtual function for setting a property
a serializable object
a property description
the property value to set
virtual function for getting a property
a serializable object
a property description
return location for the property value
The version of JSON-GLib, encoded as a string, useful for printing and
concatenation.
Checks whether it is possible to deserialize a `GBoxed` of
type `gboxed_type` from a [struct@Json.Node] of type `node_type`.
`TRUE` if the type can be deserialized, and `FALSE` otherwise
a boxed type
a node type
Checks whether it is possible to serialize a `GBoxed` of
type `gboxed_type` into a [struct@Json.Node].
The type of the node is placed inside `node_type` if the function
returns `TRUE`, and it's undefined otherwise.
`TRUE` if the type can be serialized, and `FALSE` otherwise
a boxed type
the node type to which the boxed type
can be serialized into
Deserializes the given [struct@Json.Node] into a `GBoxed` of the given type.
the newly allocated boxed data
a boxed type
a node
Registers a deserialization function for a `GBoxed` of type `gboxed_type`
from a [struct@Json.Node] of type `node_type`.
a boxed type
a node type
deserialization function
Registers a serialization function for a `GBoxed` of type `gboxed_type`
to a [struct@Json.Node] of type `node_type`.
a boxed type
a node type
serialization function
Serializes a pointer to a `GBoxed` of the given type into a [struct@Json.Node].
If the serialization is not possible, this function will return `NULL`.
a node with the serialized boxed type
a boxed type
a pointer to a boxed of type `gboxed_type`
Deserializes a JSON data stream and creates an instance of the given
type.
If the given type implements the [iface@Json.Serializable] interface, it
will be asked to deserialize all the JSON members into their respective
properties; otherwise, the default implementation will be used to translate
the compatible JSON native types.
**Note**: the JSON data stream must be an object.
For historical reasons, the `length` argument is unused. The given `data`
must be a `NUL`-terminated string.
Use [func@Json.gobject_from_data] instead
a new object instance of the given
type
the type of the object to construct
a JSON data stream
length of the data stream (unused)
Parses the given string and returns the corresponding JSON tree.
If the string is empty, this function will return `NULL`.
In case of parsing error, this function returns `NULL` and sets
the error appropriately.
the root node of the JSON tree
a valid UTF-8 string containing JSON data
Creates a new `GObject` instance of the given type, and constructs it
using the members of the object in the given node.
The newly created instance
the type of the object to create
a node of type `JSON_NODE_OBJECT` describing the
object instance for the given type
Deserializes a JSON data stream and creates an instance of the
given type.
If the type implements the [iface@Json.Serializable] interface, it will
be asked to deserialize all the JSON members into their respective properties;
otherwise, the default implementation will be used to translate the
compatible JSON native types.
**Note**: the JSON data stream must be an object
a new object instance of the given type
the type of the object to construct
a JSON data stream
length of the data stream, or -1 if it is `NUL`-terminated
Creates a JSON tree representing the passed object instance.
Each member of the returned JSON object will map to a property of
the object type.
The returned JSON tree will be returned as a `JsonNode` with a type
of `JSON_NODE_OBJECT`.
the newly created JSON tree
the object to serialize
Serializes a `GObject` instance into a JSON data stream, iterating
recursively over each property.
If the given object implements the [iface@Json.Serializable] interface,
it will be asked to serialize all its properties; otherwise, the default
implementation will be use to translate the compatible types into
JSON native types.
a JSON data stream representing the given object
the object to serialize
return value for the length of the buffer
Converts a JSON data structure to a `GVariant`.
If `signature` is not `NULL`, it will be used to resolve ambiguous
data types.
If no error occurs, the resulting `GVariant` is guaranteed to conform
to `signature`.
If `signature` is not `NULL` but does not represent a valid `GVariant` type
string, `NULL` is returned and the `error` is set to
`G_IO_ERROR_INVALID_ARGUMENT`.
If a `signature` is provided but the JSON structure cannot be mapped to it,
`NULL` is returned and the `error` is set to `G_IO_ERROR_INVALID_DATA`.
If `signature` is `NULL`, the conversion is done based strictly on the types
in the JSON nodes.
The returned variant has a floating reference that will need to be sunk
by the caller code.
A newly created `GVariant`
the node to convert
a valid `GVariant` type string
Converts a JSON string to a `GVariant` value.
This function works exactly like [func@Json.gvariant_deserialize], but
takes a JSON encoded string instead.
The string is first converted to a [struct@Json.Node] using
[class@Json.Parser], and then `json_gvariant_deserialize` is called on
the node.
The returned variant has a floating reference that will need to be sunk
by the caller code.
A newly created `GVariant`D compliant
A JSON data string
The length of @json, or -1 if `NUL`-terminated
A valid `GVariant` type string
Converts `variant` to a JSON tree.
the root of the JSON data structure
obtained from `variant`
A `GVariant` to convert
Converts @variant to its JSON encoded string representation.
This is a convenience function around [func@Json.gvariant_serialize], to
obtain the JSON tree, and then [class@Json.Generator] to stringify it.
The JSON encoded string corresponding to
the given variant
A #GVariant to convert
the length of the returned string
Serializes a `GObject` instance into a JSON data stream.
If the object implements the [iface@Json.Serializable] interface, it will be
asked to serizalize all its properties; otherwise, the default
implementation will be use to translate the compatible types into JSON
native types.
Use [func@Json.gobject_to_data] instead
a JSON data stream representing the given object
the object to serialize
return value for the length of the buffer
Check whether @a and @b are equal UTF-8 JSON strings and return an ordering
over them in `strcmp()` style.
an integer less than zero if `a < b`, equal to zero if `a == b`, and
greater than zero if `a > b`
a JSON string
another JSON string
Check whether @a and @b are equal UTF-8 JSON strings.
`TRUE` if @a and @b are equal; `FALSE` otherwise
a JSON string
another JSON string
Calculate a hash value for the given @key (a UTF-8 JSON string).
Note: Member names are compared byte-wise, without applying any Unicode
decomposition or normalisation. This is not explicitly mentioned in the JSON
standard (ECMA-404), but is assumed.
hash value for @key
a JSON string to hash
Generates a stringified JSON representation of the contents of
the given `node`.
the string representation of the node
a JSON tree
whether the output should be prettyfied for printing