apiref.txt revision 4139
4139N/A.. _apiref:
4139N/A
4139N/A*************
4139N/AAPI Reference
4139N/A*************
4139N/A
4139N/A.. highlight:: c
4139N/A
4139N/APreliminaries
4139N/A=============
4139N/A
4139N/AAll declarations are in :file:`jansson.h`, so it's enough to
4139N/A
4139N/A::
4139N/A
4139N/A #include <jansson.h>
4139N/A
4139N/Ain each source file.
4139N/A
4139N/AAll constants are prefixed with ``JSON_`` (except for those describing
4139N/Athe library version, prefixed with ``JANSSON_``). Other identifiers
4139N/Aare prefixed with ``json_``. Type names are suffixed with ``_t`` and
4139N/A``typedef``\ 'd so that the ``struct`` keyword need not be used.
4139N/A
4139N/A
4139N/ALibrary Version
4139N/A===============
4139N/A
4139N/AThe Jansson version is of the form *A.B.C*, where *A* is the major
4139N/Aversion, *B* is the minor version and *C* is the micro version. If the
4139N/Amicro version is zero, it's omitted from the version string, i.e. the
4139N/Aversion string is just *A.B*.
4139N/A
4139N/AWhen a new release only fixes bugs and doesn't add new features or
4139N/Afunctionality, the micro version is incremented. When new features are
4139N/Aadded in a backwards compatible way, the minor version is incremented
4139N/Aand the micro version is set to zero. When there are backwards
4139N/Aincompatible changes, the major version is incremented and others are
4139N/Aset to zero.
4139N/A
4139N/AThe following preprocessor constants specify the current version of
4139N/Athe library:
4139N/A
4139N/A``JANSSON_MAJOR_VERSION``, ``JANSSON_MINOR_VERSION``, ``JANSSON_MICRO_VERSION``
4139N/A Integers specifying the major, minor and micro versions,
4139N/A respectively.
4139N/A
4139N/A``JANSSON_VERSION``
4139N/A A string representation of the current version, e.g. ``"1.2.1"`` or
4139N/A ``"1.3"``.
4139N/A
4139N/A``JANSSON_VERSION_HEX``
4139N/A A 3-byte hexadecimal representation of the version, e.g.
4139N/A ``0x010201`` for version 1.2.1 and ``0x010300`` for version 1.3.
4139N/A This is useful in numeric comparisions, e.g.::
4139N/A
4139N/A #if JANSSON_VERSION_HEX >= 0x010300
4139N/A /* Code specific to version 1.3 and above */
4139N/A #endif
4139N/A
4139N/A
4139N/AValue Representation
4139N/A====================
4139N/A
4139N/AThe JSON specification (:rfc:`4627`) defines the following data types:
4139N/A*object*, *array*, *string*, *number*, *boolean*, and *null*. JSON
4139N/Atypes are used dynamically; arrays and objects can hold any other data
4139N/Atype, including themselves. For this reason, Jansson's type system is
4139N/Aalso dynamic in nature. There's one C type to represent all JSON
4139N/Avalues, and this structure knows the type of the JSON value it holds.
4139N/A
4139N/A.. type:: json_t
4139N/A
4139N/A This data structure is used throughout the library to represent all
4139N/A JSON values. It always contains the type of the JSON value it holds
4139N/A and the value's reference count. The rest depends on the type of the
4139N/A value.
4139N/A
4139N/AObjects of :type:`json_t` are always used through a pointer. There
4139N/Aare APIs for querying the type, manipulating the reference count, and
4139N/Afor constructing and manipulating values of different types.
4139N/A
4139N/AUnless noted otherwise, all API functions return an error value if an
4139N/Aerror occurs. Depending on the function's signature, the error value
4139N/Ais either *NULL* or -1. Invalid arguments or invalid input are
4139N/Aapparent sources for errors. Memory allocation and I/O operations may
4139N/Aalso cause errors.
4139N/A
4139N/A
4139N/AType
4139N/A----
4139N/A
4139N/AThe type of a JSON value is queried and tested using the following
4139N/Afunctions:
4139N/A
4139N/A.. type:: enum json_type
4139N/A
4139N/A The type of a JSON value. The following members are defined:
4139N/A
4139N/A +--------------------+
4139N/A | ``JSON_OBJECT`` |
4139N/A +--------------------+
4139N/A | ``JSON_ARRAY`` |
4139N/A +--------------------+
4139N/A | ``JSON_STRING`` |
4139N/A +--------------------+
4139N/A | ``JSON_INTEGER`` |
4139N/A +--------------------+
4139N/A | ``JSON_REAL`` |
4139N/A +--------------------+
4139N/A | ``JSON_TRUE`` |
4139N/A +--------------------+
4139N/A | ``JSON_FALSE`` |
4139N/A +--------------------+
4139N/A | ``JSON_NULL`` |
4139N/A +--------------------+
4139N/A
4139N/A These correspond to JSON object, array, string, number, boolean and
4139N/A null. A number is represented by either a value of the type
4139N/A ``JSON_INTEGER`` or of the type ``JSON_REAL``. A true boolean value
4139N/A is represented by a value of the type ``JSON_TRUE`` and false by a
4139N/A value of the type ``JSON_FALSE``.
4139N/A
4139N/A.. function:: int json_typeof(const json_t *json)
4139N/A
4139N/A Return the type of the JSON value (a :type:`json_type` cast to
4139N/A :type:`int`). *json* MUST NOT be *NULL*. This function is actually
4139N/A implemented as a macro for speed.
4139N/A
4139N/A.. function:: json_is_object(const json_t *json)
4139N/A json_is_array(const json_t *json)
4139N/A json_is_string(const json_t *json)
4139N/A json_is_integer(const json_t *json)
4139N/A json_is_real(const json_t *json)
4139N/A json_is_true(const json_t *json)
4139N/A json_is_false(const json_t *json)
4139N/A json_is_null(const json_t *json)
4139N/A
4139N/A These functions (actually macros) return true (non-zero) for values
4139N/A of the given type, and false (zero) for values of other types and
4139N/A for *NULL*.
4139N/A
4139N/A.. function:: json_is_number(const json_t *json)
4139N/A
4139N/A Returns true for values of types ``JSON_INTEGER`` and
4139N/A ``JSON_REAL``, and false for other types and for *NULL*.
4139N/A
4139N/A.. function:: json_is_boolean(const json_t *json)
4139N/A
4139N/A Returns true for types ``JSON_TRUE`` and ``JSON_FALSE``, and false
4139N/A for values of other types and for *NULL*.
4139N/A
4139N/A.. function:: json_boolean_value(const json_t *json)
4139N/A
4139N/A Alias of :func:`json_is_true()`, i.e. returns 1 for ``JSON_TRUE``
4139N/A and 0 otherwise.
4139N/A
4139N/A .. versionadded:: 2.7
4139N/A
4139N/A
4139N/A.. _apiref-reference-count:
4139N/A
4139N/AReference Count
4139N/A---------------
4139N/A
4139N/AThe reference count is used to track whether a value is still in use
4139N/Aor not. When a value is created, it's reference count is set to 1. If
4139N/Aa reference to a value is kept (e.g. a value is stored somewhere for
4139N/Alater use), its reference count is incremented, and when the value is
4139N/Ano longer needed, the reference count is decremented. When the
4139N/Areference count drops to zero, there are no references left, and the
4139N/Avalue can be destroyed.
4139N/A
4139N/AThe following functions are used to manipulate the reference count.
4139N/A
4139N/A.. function:: json_t *json_incref(json_t *json)
4139N/A
4139N/A Increment the reference count of *json* if it's not *NULL*.
4139N/A Returns *json*.
4139N/A
4139N/A.. function:: void json_decref(json_t *json)
4139N/A
4139N/A Decrement the reference count of *json*. As soon as a call to
4139N/A :func:`json_decref()` drops the reference count to zero, the value
4139N/A is destroyed and it can no longer be used.
4139N/A
4139N/AFunctions creating new JSON values set the reference count to 1. These
4139N/Afunctions are said to return a **new reference**. Other functions
4139N/Areturning (existing) JSON values do not normally increase the
4139N/Areference count. These functions are said to return a **borrowed
4139N/Areference**. So, if the user will hold a reference to a value returned
4139N/Aas a borrowed reference, he must call :func:`json_incref`. As soon as
4139N/Athe value is no longer needed, :func:`json_decref` should be called
4139N/Ato release the reference.
4139N/A
4139N/ANormally, all functions accepting a JSON value as an argument will
4139N/Amanage the reference, i.e. increase and decrease the reference count
4139N/Aas needed. However, some functions **steal** the reference, i.e. they
4139N/Ahave the same result as if the user called :func:`json_decref()` on
4139N/Athe argument right after calling the function. These functions are
4139N/Asuffixed with ``_new`` or have ``_new_`` somewhere in their name.
4139N/A
4139N/AFor example, the following code creates a new JSON array and appends
4139N/Aan integer to it::
4139N/A
4139N/A json_t *array, *integer;
4139N/A
4139N/A array = json_array();
4139N/A integer = json_integer(42);
4139N/A
4139N/A json_array_append(array, integer);
4139N/A json_decref(integer);
4139N/A
4139N/ANote how the caller has to release the reference to the integer value
4139N/Aby calling :func:`json_decref()`. By using a reference stealing
4139N/Afunction :func:`json_array_append_new()` instead of
4139N/A:func:`json_array_append()`, the code becomes much simpler::
4139N/A
4139N/A json_t *array = json_array();
4139N/A json_array_append_new(array, json_integer(42));
4139N/A
4139N/AIn this case, the user doesn't have to explicitly release the
4139N/Areference to the integer value, as :func:`json_array_append_new()`
4139N/Asteals the reference when appending the value to the array.
4139N/A
4139N/AIn the following sections it is clearly documented whether a function
4139N/Awill return a new or borrowed reference or steal a reference to its
4139N/Aargument.
4139N/A
4139N/A
4139N/ACircular References
4139N/A-------------------
4139N/A
4139N/AA circular reference is created when an object or an array is,
4139N/Adirectly or indirectly, inserted inside itself. The direct case is
4139N/Asimple::
4139N/A
4139N/A json_t *obj = json_object();
4139N/A json_object_set(obj, "foo", obj);
4139N/A
4139N/AJansson will refuse to do this, and :func:`json_object_set()` (and
4139N/Aall the other such functions for objects and arrays) will return with
4139N/Aan error status. The indirect case is the dangerous one::
4139N/A
4139N/A json_t *arr1 = json_array(), *arr2 = json_array();
4139N/A json_array_append(arr1, arr2);
4139N/A json_array_append(arr2, arr1);
4139N/A
4139N/AIn this example, the array ``arr2`` is contained in the array
4139N/A``arr1``, and vice versa. Jansson cannot check for this kind of
4139N/Aindirect circular references without a performance hit, so it's up to
4139N/Athe user to avoid them.
4139N/A
4139N/AIf a circular reference is created, the memory consumed by the values
4139N/Acannot be freed by :func:`json_decref()`. The reference counts never
4139N/Adrops to zero because the values are keeping the references to each
4139N/Aother. Moreover, trying to encode the values with any of the encoding
4139N/Afunctions will fail. The encoder detects circular references and
4139N/Areturns an error status.
4139N/A
4139N/A
4139N/ATrue, False and Null
4139N/A====================
4139N/A
4139N/AThese three values are implemented as singletons, so the returned
4139N/Apointers won't change between invocations of these functions.
4139N/A
4139N/A.. function:: json_t *json_true(void)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Returns the JSON true value.
4139N/A
4139N/A.. function:: json_t *json_false(void)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Returns the JSON false value.
4139N/A
4139N/A.. function:: json_t *json_boolean(val)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Returns JSON false if ``val`` is zero, and JSON true otherwise.
4139N/A This is a macro, and equivalent to ``val ? json_true() :
4139N/A json_false()``.
4139N/A
4139N/A .. versionadded:: 2.4
4139N/A
4139N/A
4139N/A.. function:: json_t *json_null(void)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Returns the JSON null value.
4139N/A
4139N/A
4139N/AString
4139N/A======
4139N/A
4139N/AJansson uses UTF-8 as the character encoding. All JSON strings must be
4139N/Avalid UTF-8 (or ASCII, as it's a subset of UTF-8). All Unicode
4139N/Acodepoints U+0000 through U+10FFFF are allowed, but you must use
4139N/Alength-aware functions if you wish to embed NUL bytes in strings.
4139N/A
4139N/A.. function:: json_t *json_string(const char *value)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Returns a new JSON string, or *NULL* on error. *value* must be a
4139N/A valid null terminated UTF-8 encoded Unicode string.
4139N/A
4139N/A.. function:: json_t *json_stringn(const char *value, size_t len)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Like :func:`json_string`, but with explicit length, so *value* may
4139N/A contain null characters or not be null terminated.
4139N/A
4139N/A.. function:: json_t *json_string_nocheck(const char *value)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Like :func:`json_string`, but doesn't check that *value* is valid
4139N/A UTF-8. Use this function only if you are certain that this really
4139N/A is the case (e.g. you have already checked it by other means).
4139N/A
4139N/A.. function:: json_t *json_stringn_nocheck(const char *value, size_t len)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Like :func:`json_string_nocheck`, but with explicit length, so
4139N/A *value* may contain null characters or not be null terminated.
4139N/A
4139N/A.. function:: const char *json_string_value(const json_t *string)
4139N/A
4139N/A Returns the associated value of *string* as a null terminated UTF-8
4139N/A encoded string, or *NULL* if *string* is not a JSON string.
4139N/A
4139N/A The retuned value is read-only and must not be modified or freed by
4139N/A the user. It is valid as long as *string* exists, i.e. as long as
4139N/A its reference count has not dropped to zero.
4139N/A
4139N/A.. function:: size_t json_string_length(const json_t *string)
4139N/A
4139N/A Returns the length of *string* in its UTF-8 presentation, or zero
4139N/A if *string* is not a JSON string.
4139N/A
4139N/A.. function:: int json_string_set(const json_t *string, const char *value)
4139N/A
4139N/A Sets the associated value of *string* to *value*. *value* must be a
4139N/A valid UTF-8 encoded Unicode string. Returns 0 on success and -1 on
4139N/A error.
4139N/A
4139N/A.. function:: int json_string_setn(json_t *string, const char *value, size_t len)
4139N/A
4139N/A Like :func:`json_string_set`, but with explicit length, so *value*
4139N/A may contain null characters or not be null terminated.
4139N/A
4139N/A.. function:: int json_string_set_nocheck(const json_t *string, const char *value)
4139N/A
4139N/A Like :func:`json_string_set`, but doesn't check that *value* is
4139N/A valid UTF-8. Use this function only if you are certain that this
4139N/A really is the case (e.g. you have already checked it by other
4139N/A means).
4139N/A
4139N/A.. function:: int json_string_setn_nocheck(json_t *string, const char *value, size_t len)
4139N/A
4139N/A Like :func:`json_string_set_nocheck`, but with explicit length,
4139N/A so *value* may contain null characters or not be null terminated.
4139N/A
4139N/A
4139N/ANumber
4139N/A======
4139N/A
4139N/AThe JSON specification only contains one numeric type, "number". The C
4139N/Aprogramming language has distinct types for integer and floating-point
4139N/Anumbers, so for practical reasons Jansson also has distinct types for
4139N/Athe two. They are called "integer" and "real", respectively. For more
4139N/Ainformation, see :ref:`rfc-conformance`.
4139N/A
4139N/A.. type:: json_int_t
4139N/A
4139N/A This is the C type that is used to store JSON integer values. It
4139N/A represents the widest integer type available on your system. In
4139N/A practice it's just a typedef of ``long long`` if your compiler
4139N/A supports it, otherwise ``long``.
4139N/A
4139N/A Usually, you can safely use plain ``int`` in place of
4139N/A ``json_int_t``, and the implicit C integer conversion handles the
4139N/A rest. Only when you know that you need the full 64-bit range, you
4139N/A should use ``json_int_t`` explicitly.
4139N/A
4139N/A``JSON_INTEGER_IS_LONG_LONG``
4139N/A This is a preprocessor variable that holds the value 1 if
4139N/A :type:`json_int_t` is ``long long``, and 0 if it's ``long``. It
4139N/A can be used as follows::
4139N/A
4139N/A #if JSON_INTEGER_IS_LONG_LONG
4139N/A /* Code specific for long long */
4139N/A #else
4139N/A /* Code specific for long */
4139N/A #endif
4139N/A
4139N/A``JSON_INTEGER_FORMAT``
4139N/A This is a macro that expands to a :func:`printf()` conversion
4139N/A specifier that corresponds to :type:`json_int_t`, without the
4139N/A leading ``%`` sign, i.e. either ``"lld"`` or ``"ld"``. This macro
4139N/A is required because the actual type of :type:`json_int_t` can be
4139N/A either ``long`` or ``long long``, and :func:`printf()` reuiqres
4139N/A different length modifiers for the two.
4139N/A
4139N/A Example::
4139N/A
4139N/A json_int_t x = 123123123;
4139N/A printf("x is %" JSON_INTEGER_FORMAT "\n", x);
4139N/A
4139N/A
4139N/A.. function:: json_t *json_integer(json_int_t value)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Returns a new JSON integer, or *NULL* on error.
4139N/A
4139N/A.. function:: json_int_t json_integer_value(const json_t *integer)
4139N/A
4139N/A Returns the associated value of *integer*, or 0 if *json* is not a
4139N/A JSON integer.
4139N/A
4139N/A.. function:: int json_integer_set(const json_t *integer, json_int_t value)
4139N/A
4139N/A Sets the associated value of *integer* to *value*. Returns 0 on
4139N/A success and -1 if *integer* is not a JSON integer.
4139N/A
4139N/A.. function:: json_t *json_real(double value)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Returns a new JSON real, or *NULL* on error.
4139N/A
4139N/A.. function:: double json_real_value(const json_t *real)
4139N/A
4139N/A Returns the associated value of *real*, or 0.0 if *real* is not a
4139N/A JSON real.
4139N/A
4139N/A.. function:: int json_real_set(const json_t *real, double value)
4139N/A
4139N/A Sets the associated value of *real* to *value*. Returns 0 on
4139N/A success and -1 if *real* is not a JSON real.
4139N/A
4139N/AIn addition to the functions above, there's a common query function
4139N/Afor integers and reals:
4139N/A
4139N/A.. function:: double json_number_value(const json_t *json)
4139N/A
4139N/A Returns the associated value of the JSON integer or JSON real
4139N/A *json*, cast to double regardless of the actual type. If *json* is
4139N/A neither JSON real nor JSON integer, 0.0 is returned.
4139N/A
4139N/A
4139N/AArray
4139N/A=====
4139N/A
4139N/AA JSON array is an ordered collection of other JSON values.
4139N/A
4139N/A.. function:: json_t *json_array(void)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Returns a new JSON array, or *NULL* on error. Initially, the array
4139N/A is empty.
4139N/A
4139N/A.. function:: size_t json_array_size(const json_t *array)
4139N/A
4139N/A Returns the number of elements in *array*, or 0 if *array* is NULL
4139N/A or not a JSON array.
4139N/A
4139N/A.. function:: json_t *json_array_get(const json_t *array, size_t index)
4139N/A
4139N/A .. refcounting:: borrow
4139N/A
4139N/A Returns the element in *array* at position *index*. The valid range
4139N/A for *index* is from 0 to the return value of
4139N/A :func:`json_array_size()` minus 1. If *array* is not a JSON array,
4139N/A if *array* is *NULL*, or if *index* is out of range, *NULL* is
4139N/A returned.
4139N/A
4139N/A.. function:: int json_array_set(json_t *array, size_t index, json_t *value)
4139N/A
4139N/A Replaces the element in *array* at position *index* with *value*.
4139N/A The valid range for *index* is from 0 to the return value of
4139N/A :func:`json_array_size()` minus 1. Returns 0 on success and -1 on
4139N/A error.
4139N/A
4139N/A.. function:: int json_array_set_new(json_t *array, size_t index, json_t *value)
4139N/A
4139N/A Like :func:`json_array_set()` but steals the reference to *value*.
4139N/A This is useful when *value* is newly created and not used after
4139N/A the call.
4139N/A
4139N/A.. function:: int json_array_append(json_t *array, json_t *value)
4139N/A
4139N/A Appends *value* to the end of *array*, growing the size of *array*
4139N/A by 1. Returns 0 on success and -1 on error.
4139N/A
4139N/A.. function:: int json_array_append_new(json_t *array, json_t *value)
4139N/A
4139N/A Like :func:`json_array_append()` but steals the reference to
4139N/A *value*. This is useful when *value* is newly created and not used
4139N/A after the call.
4139N/A
4139N/A.. function:: int json_array_insert(json_t *array, size_t index, json_t *value)
4139N/A
4139N/A Inserts *value* to *array* at position *index*, shifting the
4139N/A elements at *index* and after it one position towards the end of
4139N/A the array. Returns 0 on success and -1 on error.
4139N/A
4139N/A.. function:: int json_array_insert_new(json_t *array, size_t index, json_t *value)
4139N/A
4139N/A Like :func:`json_array_insert()` but steals the reference to
4139N/A *value*. This is useful when *value* is newly created and not used
4139N/A after the call.
4139N/A
4139N/A.. function:: int json_array_remove(json_t *array, size_t index)
4139N/A
4139N/A Removes the element in *array* at position *index*, shifting the
4139N/A elements after *index* one position towards the start of the array.
4139N/A Returns 0 on success and -1 on error. The reference count of the
4139N/A removed value is decremented.
4139N/A
4139N/A.. function:: int json_array_clear(json_t *array)
4139N/A
4139N/A Removes all elements from *array*. Returns 0 on sucess and -1 on
4139N/A error. The reference count of all removed values are decremented.
4139N/A
4139N/A.. function:: int json_array_extend(json_t *array, json_t *other_array)
4139N/A
4139N/A Appends all elements in *other_array* to the end of *array*.
4139N/A Returns 0 on success and -1 on error.
4139N/A
4139N/AThe following macro can be used to iterate through all elements
4139N/Ain an array.
4139N/A
4139N/A.. function:: json_array_foreach(array, index, value)
4139N/A
4139N/A Iterate over every element of ``array``, running the block
4139N/A of code that follows each time with the proper values set to
4139N/A variables ``index`` and ``value``, of types :type:`size_t` and
4139N/A :type:`json_t *` respectively. Example::
4139N/A
4139N/A /* array is a JSON array */
4139N/A size_t index;
4139N/A json_t *value;
4139N/A
4139N/A json_array_foreach(array, index, value) {
4139N/A /* block of code that uses index and value */
4139N/A }
4139N/A
4139N/A The items are returned in increasing index order.
4139N/A
4139N/A This macro expands to an ordinary ``for`` statement upon
4139N/A preprocessing, so its performance is equivalent to that of
4139N/A hand-written code using the array access functions.
4139N/A The main advantage of this macro is that it abstracts
4139N/A away the complexity, and makes for shorter, more
4139N/A concise code.
4139N/A
4139N/A .. versionadded:: 2.5
4139N/A
4139N/A
4139N/AObject
4139N/A======
4139N/A
4139N/AA JSON object is a dictionary of key-value pairs, where the key is a
4139N/AUnicode string and the value is any JSON value.
4139N/A
4139N/AEven though NUL bytes are allowed in string values, they are not
4139N/Aallowed in object keys.
4139N/A
4139N/A.. function:: json_t *json_object(void)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Returns a new JSON object, or *NULL* on error. Initially, the
4139N/A object is empty.
4139N/A
4139N/A.. function:: size_t json_object_size(const json_t *object)
4139N/A
4139N/A Returns the number of elements in *object*, or 0 if *object* is not
4139N/A a JSON object.
4139N/A
4139N/A.. function:: json_t *json_object_get(const json_t *object, const char *key)
4139N/A
4139N/A .. refcounting:: borrow
4139N/A
4139N/A Get a value corresponding to *key* from *object*. Returns *NULL* if
4139N/A *key* is not found and on error.
4139N/A
4139N/A.. function:: int json_object_set(json_t *object, const char *key, json_t *value)
4139N/A
4139N/A Set the value of *key* to *value* in *object*. *key* must be a
4139N/A valid null terminated UTF-8 encoded Unicode string. If there
4139N/A already is a value for *key*, it is replaced by the new value.
4139N/A Returns 0 on success and -1 on error.
4139N/A
4139N/A.. function:: int json_object_set_nocheck(json_t *object, const char *key, json_t *value)
4139N/A
4139N/A Like :func:`json_object_set`, but doesn't check that *key* is
4139N/A valid UTF-8. Use this function only if you are certain that this
4139N/A really is the case (e.g. you have already checked it by other
4139N/A means).
4139N/A
4139N/A.. function:: int json_object_set_new(json_t *object, const char *key, json_t *value)
4139N/A
4139N/A Like :func:`json_object_set()` but steals the reference to
4139N/A *value*. This is useful when *value* is newly created and not used
4139N/A after the call.
4139N/A
4139N/A.. function:: int json_object_set_new_nocheck(json_t *object, const char *key, json_t *value)
4139N/A
4139N/A Like :func:`json_object_set_new`, but doesn't check that *key* is
4139N/A valid UTF-8. Use this function only if you are certain that this
4139N/A really is the case (e.g. you have already checked it by other
4139N/A means).
4139N/A
4139N/A.. function:: int json_object_del(json_t *object, const char *key)
4139N/A
4139N/A Delete *key* from *object* if it exists. Returns 0 on success, or
4139N/A -1 if *key* was not found. The reference count of the removed value
4139N/A is decremented.
4139N/A
4139N/A.. function:: int json_object_clear(json_t *object)
4139N/A
4139N/A Remove all elements from *object*. Returns 0 on success and -1 if
4139N/A *object* is not a JSON object. The reference count of all removed
4139N/A values are decremented.
4139N/A
4139N/A.. function:: int json_object_update(json_t *object, json_t *other)
4139N/A
4139N/A Update *object* with the key-value pairs from *other*, overwriting
4139N/A existing keys. Returns 0 on success or -1 on error.
4139N/A
4139N/A.. function:: int json_object_update_existing(json_t *object, json_t *other)
4139N/A
4139N/A Like :func:`json_object_update()`, but only the values of existing
4139N/A keys are updated. No new keys are created. Returns 0 on success or
4139N/A -1 on error.
4139N/A
4139N/A .. versionadded:: 2.3
4139N/A
4139N/A.. function:: int json_object_update_missing(json_t *object, json_t *other)
4139N/A
4139N/A Like :func:`json_object_update()`, but only new keys are created.
4139N/A The value of any existing key is not changed. Returns 0 on success
4139N/A or -1 on error.
4139N/A
4139N/A .. versionadded:: 2.3
4139N/A
4139N/AThe following macro can be used to iterate through all key-value pairs
4139N/Ain an object.
4139N/A
4139N/A.. function:: json_object_foreach(object, key, value)
4139N/A
4139N/A Iterate over every key-value pair of ``object``, running the block
4139N/A of code that follows each time with the proper values set to
4139N/A variables ``key`` and ``value``, of types :type:`const char *` and
4139N/A :type:`json_t *` respectively. Example::
4139N/A
4139N/A /* obj is a JSON object */
4139N/A const char *key;
4139N/A json_t *value;
4139N/A
4139N/A json_object_foreach(obj, key, value) {
4139N/A /* block of code that uses key and value */
4139N/A }
4139N/A
4139N/A The items are not returned in any particular order.
4139N/A
4139N/A This macro expands to an ordinary ``for`` statement upon
4139N/A preprocessing, so its performance is equivalent to that of
4139N/A hand-written iteration code using the object iteration protocol
4139N/A (see below). The main advantage of this macro is that it abstracts
4139N/A away the complexity behind iteration, and makes for shorter, more
4139N/A concise code.
4139N/A
4139N/A .. versionadded:: 2.3
4139N/A
4139N/A
4139N/AThe following functions implement an iteration protocol for objects,
4139N/Aallowing to iterate through all key-value pairs in an object. The
4139N/Aitems are not returned in any particular order, as this would require
4139N/Asorting due to the internal hashtable implementation.
4139N/A
4139N/A.. function:: void *json_object_iter(json_t *object)
4139N/A
4139N/A Returns an opaque iterator which can be used to iterate over all
4139N/A key-value pairs in *object*, or *NULL* if *object* is empty.
4139N/A
4139N/A.. function:: void *json_object_iter_at(json_t *object, const char *key)
4139N/A
4139N/A Like :func:`json_object_iter()`, but returns an iterator to the
4139N/A key-value pair in *object* whose key is equal to *key*, or NULL if
4139N/A *key* is not found in *object*. Iterating forward to the end of
4139N/A *object* only yields all key-value pairs of the object if *key*
4139N/A happens to be the first key in the underlying hash table.
4139N/A
4139N/A.. function:: void *json_object_iter_next(json_t *object, void *iter)
4139N/A
4139N/A Returns an iterator pointing to the next key-value pair in *object*
4139N/A after *iter*, or *NULL* if the whole object has been iterated
4139N/A through.
4139N/A
4139N/A.. function:: const char *json_object_iter_key(void *iter)
4139N/A
4139N/A Extract the associated key from *iter*.
4139N/A
4139N/A.. function:: json_t *json_object_iter_value(void *iter)
4139N/A
4139N/A .. refcounting:: borrow
4139N/A
4139N/A Extract the associated value from *iter*.
4139N/A
4139N/A.. function:: int json_object_iter_set(json_t *object, void *iter, json_t *value)
4139N/A
4139N/A Set the value of the key-value pair in *object*, that is pointed to
4139N/A by *iter*, to *value*.
4139N/A
4139N/A.. function:: int json_object_iter_set_new(json_t *object, void *iter, json_t *value)
4139N/A
4139N/A Like :func:`json_object_iter_set()`, but steals the reference to
4139N/A *value*. This is useful when *value* is newly created and not used
4139N/A after the call.
4139N/A
4139N/A.. function:: void *json_object_key_to_iter(const char *key)
4139N/A
4139N/A Like :func:`json_object_iter_at()`, but much faster. Only works for
4139N/A values returned by :func:`json_object_iter_key()`. Using other keys
4139N/A will lead to segfaults. This function is used internally to
4139N/A implement :func:`json_object_foreach`.
4139N/A
4139N/A .. versionadded:: 2.3
4139N/A
4139N/AThe iteration protocol can be used for example as follows::
4139N/A
4139N/A /* obj is a JSON object */
4139N/A const char *key;
4139N/A json_t *value;
4139N/A
4139N/A void *iter = json_object_iter(obj);
4139N/A while(iter)
4139N/A {
4139N/A key = json_object_iter_key(iter);
4139N/A value = json_object_iter_value(iter);
4139N/A /* use key and value ... */
4139N/A iter = json_object_iter_next(obj, iter);
4139N/A }
4139N/A
4139N/A.. function:: void json_object_seed(size_t seed)
4139N/A
4139N/A Seed the hash function used in Jansson's hashtable implementation.
4139N/A The seed is used to randomize the hash function so that an
4139N/A attacker cannot control its output.
4139N/A
4139N/A If *seed* is 0, Jansson generates the seed itselfy by reading
4139N/A random data from the operating system's entropy sources. If no
4139N/A entropy sources are available, falls back to using a combination
4139N/A of the current timestamp (with microsecond precision if possible)
4139N/A and the process ID.
4139N/A
4139N/A If called at all, this function must be called before any calls to
4139N/A :func:`json_object()`, either explicit or implicit. If this
4139N/A function is not called by the user, the first call to
4139N/A :func:`json_object()` (either explicit or implicit) seeds the hash
4139N/A function. See :ref:`portability-thread-safety` for notes on thread
4139N/A safety.
4139N/A
4139N/A If repeatable results are required, for e.g. unit tests, the hash
4139N/A function can be "unrandomized" by calling :func:`json_object_seed`
4139N/A with a constant value on program startup, e.g.
4139N/A ``json_object_seed(1)``.
4139N/A
4139N/A .. versionadded:: 2.6
4139N/A
4139N/A
4139N/AError reporting
4139N/A===============
4139N/A
4139N/AJansson uses a single struct type to pass error information to the
4139N/Auser. See sections :ref:`apiref-decoding`, :ref:`apiref-pack` and
4139N/A:ref:`apiref-unpack` for functions that pass error information using
4139N/Athis struct.
4139N/A
4139N/A.. type:: json_error_t
4139N/A
4139N/A .. member:: char text[]
4139N/A
4139N/A The error message (in UTF-8), or an empty string if a message is
4139N/A not available.
4139N/A
4139N/A .. member:: char source[]
4139N/A
4139N/A Source of the error. This can be (a part of) the file name or a
4139N/A special identifier in angle brackers (e.g. ``<string>``).
4139N/A
4139N/A .. member:: int line
4139N/A
4139N/A The line number on which the error occurred.
4139N/A
4139N/A .. member:: int column
4139N/A
4139N/A The column on which the error occurred. Note that this is the
4139N/A *character column*, not the byte column, i.e. a multibyte UTF-8
4139N/A character counts as one column.
4139N/A
4139N/A .. member:: size_t position
4139N/A
4139N/A The position in bytes from the start of the input. This is
4139N/A useful for debugging Unicode encoding problems.
4139N/A
4139N/AThe normal use of :type:`json_error_t` is to allocate it on the stack,
4139N/Aand pass a pointer to a function. Example::
4139N/A
4139N/A int main() {
4139N/A json_t *json;
4139N/A json_error_t error;
4139N/A
4139N/A json = json_load_file("/path/to/file.json", 0, &error);
4139N/A if(!json) {
4139N/A /* the error variable contains error information */
4139N/A }
4139N/A ...
4139N/A }
4139N/A
4139N/AAlso note that if the call succeeded (``json != NULL`` in the above
4139N/Aexample), the contents of ``error`` are generally left unspecified.
4139N/AThe decoding functions write to the ``position`` member also on
4139N/Asuccess. See :ref:`apiref-decoding` for more info.
4139N/A
4139N/AAll functions also accept *NULL* as the :type:`json_error_t` pointer,
4139N/Ain which case no error information is returned to the caller.
4139N/A
4139N/A
4139N/AEncoding
4139N/A========
4139N/A
4139N/AThis sections describes the functions that can be used to encode
4139N/Avalues to JSON. By default, only objects and arrays can be encoded
4139N/Adirectly, since they are the only valid *root* values of a JSON text.
4139N/ATo encode any JSON value, use the ``JSON_ENCODE_ANY`` flag (see
4139N/Abelow).
4139N/A
4139N/ABy default, the output has no newlines, and spaces are used between
4139N/Aarray and object elements for a readable output. This behavior can be
4139N/Aaltered by using the ``JSON_INDENT`` and ``JSON_COMPACT`` flags
4139N/Adescribed below. A newline is never appended to the end of the encoded
4139N/AJSON data.
4139N/A
4139N/AEach function takes a *flags* parameter that controls some aspects of
4139N/Ahow the data is encoded. Its default value is 0. The following macros
4139N/Acan be ORed together to obtain *flags*.
4139N/A
4139N/A``JSON_INDENT(n)``
4139N/A Pretty-print the result, using newlines between array and object
4139N/A items, and indenting with *n* spaces. The valid range for *n* is
4139N/A between 0 and 31 (inclusive), other values result in an undefined
4139N/A output. If ``JSON_INDENT`` is not used or *n* is 0, no newlines are
4139N/A inserted between array and object items.
4139N/A
4139N/A The ``JSON_MAX_INDENT`` constant defines the maximum indentation
4139N/A that can be used, and its value is 31.
4139N/A
4139N/A .. versionchanged:: 2.7
4139N/A Added ``JSON_MAX_INDENT``.
4139N/A
4139N/A``JSON_COMPACT``
4139N/A This flag enables a compact representation, i.e. sets the separator
4139N/A between array and object items to ``","`` and between object keys
4139N/A and values to ``":"``. Without this flag, the corresponding
4139N/A separators are ``", "`` and ``": "`` for more readable output.
4139N/A
4139N/A``JSON_ENSURE_ASCII``
4139N/A If this flag is used, the output is guaranteed to consist only of
4139N/A ASCII characters. This is achived by escaping all Unicode
4139N/A characters outside the ASCII range.
4139N/A
4139N/A``JSON_SORT_KEYS``
4139N/A If this flag is used, all the objects in output are sorted by key.
4139N/A This is useful e.g. if two JSON texts are diffed or visually
4139N/A compared.
4139N/A
4139N/A``JSON_PRESERVE_ORDER``
4139N/A If this flag is used, object keys in the output are sorted into the
4139N/A same order in which they were first inserted to the object. For
4139N/A example, decoding a JSON text and then encoding with this flag
4139N/A preserves the order of object keys.
4139N/A
4139N/A``JSON_ENCODE_ANY``
4139N/A Specifying this flag makes it possible to encode any JSON value on
4139N/A its own. Without it, only objects and arrays can be passed as the
4139N/A *root* value to the encoding functions.
4139N/A
4139N/A **Note:** Encoding any value may be useful in some scenarios, but
4139N/A it's generally discouraged as it violates strict compatiblity with
4139N/A :rfc:`4627`. If you use this flag, don't expect interoperatibility
4139N/A with other JSON systems.
4139N/A
4139N/A .. versionadded:: 2.1
4139N/A
4139N/A``JSON_ESCAPE_SLASH``
4139N/A Escape the ``/`` characters in strings with ``\/``.
4139N/A
4139N/A .. versionadded:: 2.4
4139N/A
4139N/A``JSON_REAL_PRECISION(n)``
4139N/A Output all real numbers with at most *n* digits of precision. The
4139N/A valid range for *n* is between 0 and 31 (inclusive), and other
4139N/A values result in an undefined behavior.
4139N/A
4139N/A By default, the precision is 17, to correctly and losslessly encode
4139N/A all IEEE 754 double precision floating point numbers.
4139N/A
4139N/A .. versionadded:: 2.7
4139N/A
4139N/AThe following functions perform the actual JSON encoding. The result
4139N/Ais in UTF-8.
4139N/A
4139N/A.. function:: char *json_dumps(const json_t *root, size_t flags)
4139N/A
4139N/A Returns the JSON representation of *root* as a string, or *NULL* on
4139N/A error. *flags* is described above. The return value must be freed
4139N/A by the caller using :func:`free()`.
4139N/A
4139N/A.. function:: int json_dumpf(const json_t *root, FILE *output, size_t flags)
4139N/A
4139N/A Write the JSON representation of *root* to the stream *output*.
4139N/A *flags* is described above. Returns 0 on success and -1 on error.
4139N/A If an error occurs, something may have already been written to
4139N/A *output*. In this case, the output is undefined and most likely not
4139N/A valid JSON.
4139N/A
4139N/A.. function:: int json_dump_file(const json_t *json, const char *path, size_t flags)
4139N/A
4139N/A Write the JSON representation of *root* to the file *path*. If
4139N/A *path* already exists, it is overwritten. *flags* is described
4139N/A above. Returns 0 on success and -1 on error.
4139N/A
4139N/A.. type:: json_dump_callback_t
4139N/A
4139N/A A typedef for a function that's called by
4139N/A :func:`json_dump_callback()`::
4139N/A
4139N/A typedef int (*json_dump_callback_t)(const char *buffer, size_t size, void *data);
4139N/A
4139N/A *buffer* points to a buffer containing a chunk of output, *size* is
4139N/A the length of the buffer, and *data* is the corresponding
4139N/A :func:`json_dump_callback()` argument passed through.
4139N/A
4139N/A On error, the function should return -1 to stop the encoding
4139N/A process. On success, it should return 0.
4139N/A
4139N/A .. versionadded:: 2.2
4139N/A
4139N/A.. function:: int json_dump_callback(const json_t *json, json_dump_callback_t callback, void *data, size_t flags)
4139N/A
4139N/A Call *callback* repeatedly, passing a chunk of the JSON
4139N/A representation of *root* each time. *flags* is described above.
4139N/A Returns 0 on success and -1 on error.
4139N/A
4139N/A .. versionadded:: 2.2
4139N/A
4139N/A
4139N/A.. _apiref-decoding:
4139N/A
4139N/ADecoding
4139N/A========
4139N/A
4139N/AThis sections describes the functions that can be used to decode JSON
4139N/Atext to the Jansson representation of JSON data. The JSON
4139N/Aspecification requires that a JSON text is either a serialized array
4139N/Aor object, and this requirement is also enforced with the following
4139N/Afunctions. In other words, the top level value in the JSON text being
4139N/Adecoded must be either array or object. To decode any JSON value, use
4139N/Athe ``JSON_DECODE_ANY`` flag (see below).
4139N/A
4139N/ASee :ref:`rfc-conformance` for a discussion on Jansson's conformance
4139N/Ato the JSON specification. It explains many design decisions that
4139N/Aaffect especially the behavior of the decoder.
4139N/A
4139N/AEach function takes a *flags* parameter that can be used to control
4139N/Athe behavior of the decoder. Its default value is 0. The following
4139N/Amacros can be ORed together to obtain *flags*.
4139N/A
4139N/A``JSON_REJECT_DUPLICATES``
4139N/A Issue a decoding error if any JSON object in the input text
4139N/A contains duplicate keys. Without this flag, the value of the last
4139N/A occurence of each key ends up in the result. Key equivalence is
4139N/A checked byte-by-byte, without special Unicode comparison
4139N/A algorithms.
4139N/A
4139N/A .. versionadded:: 2.1
4139N/A
4139N/A``JSON_DECODE_ANY``
4139N/A By default, the decoder expects an array or object as the input.
4139N/A With this flag enabled, the decoder accepts any valid JSON value.
4139N/A
4139N/A **Note:** Decoding any value may be useful in some scenarios, but
4139N/A it's generally discouraged as it violates strict compatiblity with
4139N/A :rfc:`4627`. If you use this flag, don't expect interoperatibility
4139N/A with other JSON systems.
4139N/A
4139N/A .. versionadded:: 2.3
4139N/A
4139N/A``JSON_DISABLE_EOF_CHECK``
4139N/A By default, the decoder expects that its whole input constitutes a
4139N/A valid JSON text, and issues an error if there's extra data after
4139N/A the otherwise valid JSON input. With this flag enabled, the decoder
4139N/A stops after decoding a valid JSON array or object, and thus allows
4139N/A extra data after the JSON text.
4139N/A
4139N/A Normally, reading will stop when the last ``]`` or ``}`` in the
4139N/A JSON input is encountered. If both ``JSON_DISABLE_EOF_CHECK`` and
4139N/A ``JSON_DECODE_ANY`` flags are used, the decoder may read one extra
4139N/A UTF-8 code unit (up to 4 bytes of input). For example, decoding
4139N/A ``4true`` correctly decodes the integer 4, but also reads the
4139N/A ``t``. For this reason, if reading multiple consecutive values that
4139N/A are not arrays or objects, they should be separated by at least one
4139N/A whitespace character.
4139N/A
4139N/A .. versionadded:: 2.1
4139N/A
4139N/A``JSON_DECODE_INT_AS_REAL``
4139N/A JSON defines only one number type. Jansson distinguishes between
4139N/A ints and reals. For more information see :ref:`real-vs-integer`.
4139N/A With this flag enabled the decoder interprets all numbers as real
4139N/A values. Integers that do not have an exact double representation
4139N/A will silently result in a loss of precision. Integers that cause
4139N/A a double overflow will cause an error.
4139N/A
4139N/A .. versionadded:: 2.5
4139N/A
4139N/A``JSON_ALLOW_NUL``
4139N/A Allow ``\u0000`` escape inside string values. This is a safety
4139N/A measure; If you know your input can contain NUL bytes, use this
4139N/A flag. If you don't use this flag, you don't have to worry about NUL
4139N/A bytes inside strings unless you explicitly create themselves by
4139N/A using e.g. :func:`json_stringn()` or ``s#`` format specifier for
4139N/A :func:`json_pack()`.
4139N/A
4139N/A Object keys cannot have embedded NUL bytes even if this flag is
4139N/A used.
4139N/A
4139N/A .. versionadded:: 2.6
4139N/A
4139N/AEach function also takes an optional :type:`json_error_t` parameter
4139N/Athat is filled with error information if decoding fails. It's also
4139N/Aupdated on success; the number of bytes of input read is written to
4139N/Aits ``position`` field. This is especially useful when using
4139N/A``JSON_DISABLE_EOF_CHECK`` to read multiple consecutive JSON texts.
4139N/A
4139N/A.. versionadded:: 2.3
4139N/A Number of bytes of input read is written to the ``position`` field
4139N/A of the :type:`json_error_t` structure.
4139N/A
4139N/AIf no error or position information is needed, you can pass *NULL*.
4139N/A
4139N/AThe following functions perform the actual JSON decoding.
4139N/A
4139N/A.. function:: json_t *json_loads(const char *input, size_t flags, json_error_t *error)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Decodes the JSON string *input* and returns the array or object it
4139N/A contains, or *NULL* on error, in which case *error* is filled with
4139N/A information about the error. *flags* is described above.
4139N/A
4139N/A.. function:: json_t *json_loadb(const char *buffer, size_t buflen, size_t flags, json_error_t *error)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Decodes the JSON string *buffer*, whose length is *buflen*, and
4139N/A returns the array or object it contains, or *NULL* on error, in
4139N/A which case *error* is filled with information about the error. This
4139N/A is similar to :func:`json_loads()` except that the string doesn't
4139N/A need to be null-terminated. *flags* is described above.
4139N/A
4139N/A .. versionadded:: 2.1
4139N/A
4139N/A.. function:: json_t *json_loadf(FILE *input, size_t flags, json_error_t *error)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Decodes the JSON text in stream *input* and returns the array or
4139N/A object it contains, or *NULL* on error, in which case *error* is
4139N/A filled with information about the error. *flags* is described
4139N/A above.
4139N/A
4139N/A This function will start reading the input from whatever position
4139N/A the input file was, without attempting to seek first. If an error
4139N/A occurs, the file position will be left indeterminate. On success,
4139N/A the file position will be at EOF, unless ``JSON_DISABLE_EOF_CHECK``
4139N/A flag was used. In this case, the file position will be at the first
4139N/A character after the last ``]`` or ``}`` in the JSON input. This
4139N/A allows calling :func:`json_loadf()` on the same ``FILE`` object
4139N/A multiple times, if the input consists of consecutive JSON texts,
4139N/A possibly separated by whitespace.
4139N/A
4139N/A.. function:: json_t *json_load_file(const char *path, size_t flags, json_error_t *error)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Decodes the JSON text in file *path* and returns the array or
4139N/A object it contains, or *NULL* on error, in which case *error* is
4139N/A filled with information about the error. *flags* is described
4139N/A above.
4139N/A
4139N/A.. type:: json_load_callback_t
4139N/A
4139N/A A typedef for a function that's called by
4139N/A :func:`json_load_callback()` to read a chunk of input data::
4139N/A
4139N/A typedef size_t (*json_load_callback_t)(void *buffer, size_t buflen, void *data);
4139N/A
4139N/A *buffer* points to a buffer of *buflen* bytes, and *data* is the
4139N/A corresponding :func:`json_load_callback()` argument passed through.
4139N/A
4139N/A On success, the function should return the number of bytes read; a
4139N/A returned value of 0 indicates that no data was read and that the
4139N/A end of file has been reached. On error, the function should return
4139N/A ``(size_t)-1`` to abort the decoding process.
4139N/A
4139N/A .. versionadded:: 2.4
4139N/A
4139N/A.. function:: json_t *json_load_callback(json_load_callback_t callback, void *data, size_t flags, json_error_t *error)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Decodes the JSON text produced by repeated calls to *callback*, and
4139N/A returns the array or object it contains, or *NULL* on error, in
4139N/A which case *error* is filled with information about the error.
4139N/A *data* is passed through to *callback* on each call. *flags* is
4139N/A described above.
4139N/A
4139N/A .. versionadded:: 2.4
4139N/A
4139N/A
4139N/A.. _apiref-pack:
4139N/A
4139N/ABuilding Values
4139N/A===============
4139N/A
4139N/AThis section describes functions that help to create, or *pack*,
4139N/Acomplex JSON values, especially nested objects and arrays. Value
4139N/Abuilding is based on a *format string* that is used to tell the
4139N/Afunctions about the expected arguments.
4139N/A
4139N/AFor example, the format string ``"i"`` specifies a single integer
4139N/Avalue, while the format string ``"[ssb]"`` or the equivalent ``"[s, s,
4139N/Ab]"`` specifies an array value with two strings and a boolean as its
4139N/Aitems::
4139N/A
4139N/A /* Create the JSON integer 42 */
4139N/A json_pack("i", 42);
4139N/A
4139N/A /* Create the JSON array ["foo", "bar", true] */
4139N/A json_pack("[ssb]", "foo", "bar", 1);
4139N/A
4139N/AHere's the full list of format specifiers. The type in parentheses
4139N/Adenotes the resulting JSON type, and the type in brackets (if any)
4139N/Adenotes the C type that is expected as the corresponding argument or
4139N/Aarguments.
4139N/A
4139N/A``s`` (string) [const char \*]
4139N/A Convert a NULL terminated UTF-8 string to a JSON string.
4139N/A
4139N/A``s#`` (string) [const char \*, int]
4139N/A Convert a UTF-8 buffer of a given length to a JSON string.
4139N/A
4139N/A .. versionadded:: 2.5
4139N/A
4139N/A``s%`` (string) [const char \*, size_t]
4139N/A Like ``s#`` but the length argument is of type :type:`size_t`.
4139N/A
4139N/A .. versionadded:: 2.6
4139N/A
4139N/A``+`` [const char \*]
4139N/A Like ``s``, but concatenate to the previous string. Only valid
4139N/A after ``s``, ``s#``, ``+`` or ``+#``.
4139N/A
4139N/A .. versionadded:: 2.5
4139N/A
4139N/A``+#`` [const char \*, int]
4139N/A Like ``s#``, but concatenate to the previous string. Only valid
4139N/A after ``s``, ``s#``, ``+`` or ``+#``.
4139N/A
4139N/A .. versionadded:: 2.5
4139N/A
4139N/A``+%`` (string) [const char \*, size_t]
4139N/A Like ``+#`` but the length argument is of type :type:`size_t`.
4139N/A
4139N/A .. versionadded:: 2.6
4139N/A
4139N/A``n`` (null)
4139N/A Output a JSON null value. No argument is consumed.
4139N/A
4139N/A``b`` (boolean) [int]
4139N/A Convert a C :type:`int` to JSON boolean value. Zero is converted
4139N/A to ``false`` and non-zero to ``true``.
4139N/A
4139N/A``i`` (integer) [int]
4139N/A Convert a C :type:`int` to JSON integer.
4139N/A
4139N/A``I`` (integer) [json_int_t]
4139N/A Convert a C :type:`json_int_t` to JSON integer.
4139N/A
4139N/A``f`` (real) [double]
4139N/A Convert a C :type:`double` to JSON real.
4139N/A
4139N/A``o`` (any value) [json_t \*]
4139N/A Output any given JSON value as-is. If the value is added to an
4139N/A array or object, the reference to the value passed to ``o`` is
4139N/A stolen by the container.
4139N/A
4139N/A``O`` (any value) [json_t \*]
4139N/A Like ``o``, but the argument's reference count is incremented.
4139N/A This is useful if you pack into an array or object and want to
4139N/A keep the reference for the JSON value consumed by ``O`` to
4139N/A yourself.
4139N/A
4139N/A``[fmt]`` (array)
4139N/A Build an array with contents from the inner format string. ``fmt``
4139N/A may contain objects and arrays, i.e. recursive value building is
4139N/A supported.
4139N/A
4139N/A``{fmt}`` (object)
4139N/A Build an object with contents from the inner format string
4139N/A ``fmt``. The first, third, etc. format specifier represent a key,
4139N/A and must be a string (see ``s``, ``s#``, ``+`` and ``+#`` above),
4139N/A as object keys are always strings. The second, fourth, etc. format
4139N/A specifier represent a value. Any value may be an object or array,
4139N/A i.e. recursive value building is supported.
4139N/A
4139N/AWhitespace, ``:`` and ``,`` are ignored.
4139N/A
4139N/AThe following functions compose the value building API:
4139N/A
4139N/A.. function:: json_t *json_pack(const char *fmt, ...)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Build a new JSON value according to the format string *fmt*. For
4139N/A each format specifier (except for ``{}[]n``), one or more arguments
4139N/A are consumed and used to build the corresponding value. Returns
4139N/A *NULL* on error.
4139N/A
4139N/A.. function:: json_t *json_pack_ex(json_error_t *error, size_t flags, const char *fmt, ...)
4139N/A json_t *json_vpack_ex(json_error_t *error, size_t flags, const char *fmt, va_list ap)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Like :func:`json_pack()`, but an in the case of an error, an error
4139N/A message is written to *error*, if it's not *NULL*. The *flags*
4139N/A parameter is currently unused and should be set to 0.
4139N/A
4139N/A As only the errors in format string (and out-of-memory errors) can
4139N/A be caught by the packer, these two functions are most likely only
4139N/A useful for debugging format strings.
4139N/A
4139N/AMore examples::
4139N/A
4139N/A /* Build an empty JSON object */
4139N/A json_pack("{}");
4139N/A
4139N/A /* Build the JSON object {"foo": 42, "bar": 7} */
4139N/A json_pack("{sisi}", "foo", 42, "bar", 7);
4139N/A
4139N/A /* Like above, ':', ',' and whitespace are ignored */
4139N/A json_pack("{s:i, s:i}", "foo", 42, "bar", 7);
4139N/A
4139N/A /* Build the JSON array [[1, 2], {"cool": true}] */
4139N/A json_pack("[[i,i],{s:b}]", 1, 2, "cool", 1);
4139N/A
4139N/A /* Build a string from a non-NUL terminated buffer */
4139N/A char buffer[4] = {'t', 'e', 's', 't'};
4139N/A json_pack("s#", buffer, 4);
4139N/A
4139N/A /* Concatentate strings together to build the JSON string "foobarbaz" */
4139N/A json_pack("s++", "foo", "bar", "baz");
4139N/A
4139N/A
4139N/A.. _apiref-unpack:
4139N/A
4139N/AParsing and Validating Values
4139N/A=============================
4139N/A
4139N/AThis section describes functions that help to validate complex values
4139N/Aand extract, or *unpack*, data from them. Like :ref:`building values
4139N/A<apiref-pack>`, this is also based on format strings.
4139N/A
4139N/AWhile a JSON value is unpacked, the type specified in the format
4139N/Astring is checked to match that of the JSON value. This is the
4139N/Avalidation part of the process. In addition to this, the unpacking
4139N/Afunctions can also check that all items of arrays and objects are
4139N/Aunpacked. This check be enabled with the format specifier ``!`` or by
4139N/Ausing the flag ``JSON_STRICT``. See below for details.
4139N/A
4139N/AHere's the full list of format specifiers. The type in parentheses
4139N/Adenotes the JSON type, and the type in brackets (if any) denotes the C
4139N/Atype whose address should be passed.
4139N/A
4139N/A``s`` (string) [const char \*]
4139N/A Convert a JSON string to a pointer to a NULL terminated UTF-8
4139N/A string. The resulting string is extracted by using
4139N/A :func:`json_string_value()` internally, so it exists as long as
4139N/A there are still references to the corresponding JSON string.
4139N/A
4139N/A``s%`` (string) [const char \*, size_t \*]
4139N/A Convert a JSON string to a pointer to a NULL terminated UTF-8
4139N/A string and its length.
4139N/A
4139N/A .. versionadded:: 2.6
4139N/A
4139N/A``n`` (null)
4139N/A Expect a JSON null value. Nothing is extracted.
4139N/A
4139N/A``b`` (boolean) [int]
4139N/A Convert a JSON boolean value to a C :type:`int`, so that ``true``
4139N/A is converted to 1 and ``false`` to 0.
4139N/A
4139N/A``i`` (integer) [int]
4139N/A Convert a JSON integer to C :type:`int`.
4139N/A
4139N/A``I`` (integer) [json_int_t]
4139N/A Convert a JSON integer to C :type:`json_int_t`.
4139N/A
4139N/A``f`` (real) [double]
4139N/A Convert a JSON real to C :type:`double`.
4139N/A
4139N/A``F`` (integer or real) [double]
4139N/A Convert a JSON number (integer or real) to C :type:`double`.
4139N/A
4139N/A``o`` (any value) [json_t \*]
4139N/A Store a JSON value with no conversion to a :type:`json_t` pointer.
4139N/A
4139N/A``O`` (any value) [json_t \*]
4139N/A Like ``O``, but the JSON value's reference count is incremented.
4139N/A
4139N/A``[fmt]`` (array)
4139N/A Convert each item in the JSON array according to the inner format
4139N/A string. ``fmt`` may contain objects and arrays, i.e. recursive
4139N/A value extraction is supporetd.
4139N/A
4139N/A``{fmt}`` (object)
4139N/A Convert each item in the JSON object according to the inner format
4139N/A string ``fmt``. The first, third, etc. format specifier represent
4139N/A a key, and must be ``s``. The corresponding argument to unpack
4139N/A functions is read as the object key. The second fourth, etc.
4139N/A format specifier represent a value and is written to the address
4139N/A given as the corresponding argument. **Note** that every other
4139N/A argument is read from and every other is written to.
4139N/A
4139N/A ``fmt`` may contain objects and arrays as values, i.e. recursive
4139N/A value extraction is supporetd.
4139N/A
4139N/A .. versionadded:: 2.3
4139N/A Any ``s`` representing a key may be suffixed with a ``?`` to
4139N/A make the key optional. If the key is not found, nothing is
4139N/A extracted. See below for an example.
4139N/A
4139N/A``!``
4139N/A This special format specifier is used to enable the check that
4139N/A all object and array items are accessed, on a per-value basis. It
4139N/A must appear inside an array or object as the last format specifier
4139N/A before the closing bracket or brace. To enable the check globally,
4139N/A use the ``JSON_STRICT`` unpacking flag.
4139N/A
4139N/A``*``
4139N/A This special format specifier is the opposite of ``!``. If the
4139N/A ``JSON_STRICT`` flag is used, ``*`` can be used to disable the
4139N/A strict check on a per-value basis. It must appear inside an array
4139N/A or object as the last format specifier before the closing bracket
4139N/A or brace.
4139N/A
4139N/AWhitespace, ``:`` and ``,`` are ignored.
4139N/A
4139N/AThe following functions compose the parsing and validation API:
4139N/A
4139N/A.. function:: int json_unpack(json_t *root, const char *fmt, ...)
4139N/A
4139N/A Validate and unpack the JSON value *root* according to the format
4139N/A string *fmt*. Returns 0 on success and -1 on failure.
4139N/A
4139N/A.. function:: int json_unpack_ex(json_t *root, json_error_t *error, size_t flags, const char *fmt, ...)
4139N/A int json_vunpack_ex(json_t *root, json_error_t *error, size_t flags, const char *fmt, va_list ap)
4139N/A
4139N/A Validate and unpack the JSON value *root* according to the format
4139N/A string *fmt*. If an error occurs and *error* is not *NULL*, write
4139N/A error information to *error*. *flags* can be used to control the
4139N/A behaviour of the unpacker, see below for the flags. Returns 0 on
4139N/A success and -1 on failure.
4139N/A
4139N/A.. note::
4139N/A
4139N/A The first argument of all unpack functions is ``json_t *root``
4139N/A instead of ``const json_t *root``, because the use of ``O`` format
4139N/A specifier causes the reference count of ``root``, or some value
4139N/A reachable from ``root``, to be increased. Furthermore, the ``o``
4139N/A format specifier may be used to extract a value as-is, which allows
4139N/A modifying the structure or contents of a value reachable from
4139N/A ``root``.
4139N/A
4139N/A If the ``O`` and ``o`` format specifiers are not used, it's
4139N/A perfectly safe to cast a ``const json_t *`` variable to plain
4139N/A ``json_t *`` when used with these functions.
4139N/A
4139N/AThe following unpacking flags are available:
4139N/A
4139N/A``JSON_STRICT``
4139N/A Enable the extra validation step checking that all object and
4139N/A array items are unpacked. This is equivalent to appending the
4139N/A format specifier ``!`` to the end of every array and object in the
4139N/A format string.
4139N/A
4139N/A``JSON_VALIDATE_ONLY``
4139N/A Don't extract any data, just validate the JSON value against the
4139N/A given format string. Note that object keys must still be specified
4139N/A after the format string.
4139N/A
4139N/AExamples::
4139N/A
4139N/A /* root is the JSON integer 42 */
4139N/A int myint;
4139N/A json_unpack(root, "i", &myint);
4139N/A assert(myint == 42);
4139N/A
4139N/A /* root is the JSON object {"foo": "bar", "quux": true} */
4139N/A const char *str;
4139N/A int boolean;
4139N/A json_unpack(root, "{s:s, s:b}", "foo", &str, "quux", &boolean);
4139N/A assert(strcmp(str, "bar") == 0 && boolean == 1);
4139N/A
4139N/A /* root is the JSON array [[1, 2], {"baz": null} */
4139N/A json_error_t error;
4139N/A json_unpack_ex(root, &error, JSON_VALIDATE_ONLY, "[[i,i], {s:n}]", "baz");
4139N/A /* returns 0 for validation success, nothing is extracted */
4139N/A
4139N/A /* root is the JSON array [1, 2, 3, 4, 5] */
4139N/A int myint1, myint2;
4139N/A json_unpack(root, "[ii!]", &myint1, &myint2);
4139N/A /* returns -1 for failed validation */
4139N/A
4139N/A /* root is an empty JSON object */
4139N/A int myint = 0, myint2 = 0;
4139N/A json_unpack(root, "{s?i, s?[ii]}",
4139N/A "foo", &myint1,
4139N/A "bar", &myint2, &myint3);
4139N/A /* myint1, myint2 or myint3 is no touched as "foo" and "bar" don't exist */
4139N/A
4139N/A
4139N/AEquality
4139N/A========
4139N/A
4139N/ATesting for equality of two JSON values cannot, in general, be
4139N/Aachieved using the ``==`` operator. Equality in the terms of the
4139N/A``==`` operator states that the two :type:`json_t` pointers point to
4139N/Aexactly the same JSON value. However, two JSON values can be equal not
4139N/Aonly if they are exactly the same value, but also if they have equal
4139N/A"contents":
4139N/A
4139N/A* Two integer or real values are equal if their contained numeric
4139N/A values are equal. An integer value is never equal to a real value,
4139N/A though.
4139N/A
4139N/A* Two strings are equal if their contained UTF-8 strings are equal,
4139N/A byte by byte. Unicode comparison algorithms are not implemented.
4139N/A
4139N/A* Two arrays are equal if they have the same number of elements and
4139N/A each element in the first array is equal to the corresponding
4139N/A element in the second array.
4139N/A
4139N/A* Two objects are equal if they have exactly the same keys and the
4139N/A value for each key in the first object is equal to the value of the
4139N/A corresponding key in the second object.
4139N/A
4139N/A* Two true, false or null values have no "contents", so they are equal
4139N/A if their types are equal. (Because these values are singletons,
4139N/A their equality can actually be tested with ``==``.)
4139N/A
4139N/AThe following function can be used to test whether two JSON values are
4139N/Aequal.
4139N/A
4139N/A.. function:: int json_equal(json_t *value1, json_t *value2)
4139N/A
4139N/A Returns 1 if *value1* and *value2* are equal, as defined above.
4139N/A Returns 0 if they are inequal or one or both of the pointers are
4139N/A *NULL*.
4139N/A
4139N/A
4139N/ACopying
4139N/A=======
4139N/A
4139N/ABecause of reference counting, passing JSON values around doesn't
4139N/Arequire copying them. But sometimes a fresh copy of a JSON value is
4139N/Aneeded. For example, if you need to modify an array, but still want to
4139N/Ause the original afterwards, you should take a copy of it first.
4139N/A
4139N/AJansson supports two kinds of copying: shallow and deep. There is a
4139N/Adifference between these methods only for arrays and objects. Shallow
4139N/Acopying only copies the first level value (array or object) and uses
4139N/Athe same child values in the copied value. Deep copying makes a fresh
4139N/Acopy of the child values, too. Moreover, all the child values are deep
4139N/Acopied in a recursive fashion.
4139N/A
4139N/A.. function:: json_t *json_copy(json_t *value)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Returns a shallow copy of *value*, or *NULL* on error.
4139N/A
4139N/A.. function:: json_t *json_deep_copy(const json_t *value)
4139N/A
4139N/A .. refcounting:: new
4139N/A
4139N/A Returns a deep copy of *value*, or *NULL* on error.
4139N/A
4139N/A
4139N/A.. _apiref-custom-memory-allocation:
4139N/A
4139N/ACustom Memory Allocation
4139N/A========================
4139N/A
4139N/ABy default, Jansson uses :func:`malloc()` and :func:`free()` for
4139N/Amemory allocation. These functions can be overridden if custom
4139N/Abehavior is needed.
4139N/A
4139N/A.. type:: json_malloc_t
4139N/A
4139N/A A typedef for a function pointer with :func:`malloc()`'s
4139N/A signature::
4139N/A
4139N/A typedef void *(*json_malloc_t)(size_t);
4139N/A
4139N/A.. type:: json_free_t
4139N/A
4139N/A A typedef for a function pointer with :func:`free()`'s
4139N/A signature::
4139N/A
4139N/A typedef void (*json_free_t)(void *);
4139N/A
4139N/A.. function:: void json_set_alloc_funcs(json_malloc_t malloc_fn, json_free_t free_fn)
4139N/A
4139N/A Use *malloc_fn* instead of :func:`malloc()` and *free_fn* instead
4139N/A of :func:`free()`. This function has to be called before any other
4139N/A Jansson's API functions to ensure that all memory operations use
4139N/A the same functions.
4139N/A
4139N/A**Examples:**
4139N/A
4139N/ACircumvent problems with different CRT heaps on Windows by using
4139N/Aapplication's :func:`malloc()` and :func:`free()`::
4139N/A
4139N/A json_set_alloc_funcs(malloc, free);
4139N/A
4139N/AUse the `Boehm's conservative garbage collector`_ for memory
4139N/Aoperations::
4139N/A
4139N/A json_set_alloc_funcs(GC_malloc, GC_free);
4139N/A
4139N/A.. _Boehm's conservative garbage collector: http://www.hpl.hp.com/personal/Hans_Boehm/gc/
4139N/A
4139N/AAllow storing sensitive data (e.g. passwords or encryption keys) in
4139N/AJSON structures by zeroing all memory when freed::
4139N/A
4139N/A static void *secure_malloc(size_t size)
4139N/A {
4139N/A /* Store the memory area size in the beginning of the block */
4139N/A void *ptr = malloc(size + 8);
4139N/A *((size_t *)ptr) = size;
4139N/A return ptr + 8;
4139N/A }
4139N/A
4139N/A static void secure_free(void *ptr)
4139N/A {
4139N/A size_t size;
4139N/A
4139N/A ptr -= 8;
4139N/A size = *((size_t *)ptr);
4139N/A
4139N/A guaranteed_memset(ptr, 0, size + 8);
4139N/A free(ptr);
4139N/A }
4139N/A
4139N/A int main()
4139N/A {
4139N/A json_set_alloc_funcs(secure_malloc, secure_free);
4139N/A /* ... */
4139N/A }
4139N/A
4139N/AFor more information about the issues of storing sensitive data in
4139N/Amemory, see
4139N/Ahttp://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/protect-secrets.html.
4139N/AThe page also explains the :func:`guaranteed_memset()` function used
4139N/Ain the example and gives a sample implementation for it.