sd_json_variant_new_object — Create a JSON object variant from an array of key/value pairs
#include <systemd/sd-json.h>
int sd_json_variant_new_object( | sd_json_variant **ret, |
| sd_json_variant **array, | |
size_t n); |
sd_json_variant_new_object() allocates a new JSON object variant and returns
it in ret. The object's fields are taken from array, which
must contain n variants, alternating between keys and values: the elements at even
indexes are the keys and must be JSON string variants, each followed by the variant to use as the value
for that key. n hence must be even. The order of the fields is retained. The
referenced variants are not consumed, the new object takes its own references to them (or copies them).
If n is zero, array may be NULL and an
empty object is returned.
Each key may only be used once within the same object. If two or more keys in
array are equal (compared byte-wise, i.e. case-sensitively, after any escaping
has been resolved), the call fails with -ENOTUNIQ. JSON (as defined by
RFC 8259) recommends, but does not
require, keys to be unique, and implementations differ in how they treat duplicates. Since every JSON
object in this library is ultimately created through this function — this includes objects generated by
the parser (see
sd_json_parse(3)) and
the builder (see
sd_json_build(3)) — no
sd_json_variant object can ever contain duplicate keys. Lookups by key (e.g. via
sd_json_variant_by_key()) hence are always unambiguous.
Use sd_json_variant_set_field() or
sd_json_variant_merge_object() to derive a new object from an existing one with
fields added or replaced; these calls drop any previous field of the same name before adding the new
one, and hence do not fail on duplicate keys.
On success, sd_json_variant_new_object() returns 0. On failure, it returns a
negative errno-style error code. On failure ret is not modified.
Functions described here are available as a shared
library, which can be compiled against and linked to with the
libsystemd pkg-config(1)
file.
The code described here uses
getenv(3),
which is declared to be not multi-thread-safe. This means that the code calling the functions described
here must not call
setenv(3)
from a parallel thread. It is recommended to only do calls to setenv()
from an early phase of the program when no other threads have been started.
sd_json_variant_new_object() was added in version 257.
Before version 263 objects with duplicate keys were accepted by
sd_json_variant_new_object().