apiref.rst 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632
  1. .. _apiref:
  2. *************
  3. API Reference
  4. *************
  5. .. highlight:: c
  6. Preliminaries
  7. =============
  8. All declarations are in :file:`jansson.h`, so it's enough to
  9. ::
  10. #include <jansson.h>
  11. in each source file.
  12. All constants are prefixed with ``JSON_`` (except for those describing
  13. the library version, prefixed with ``JANSSON_``). Other identifiers
  14. are prefixed with ``json_``. Type names are suffixed with ``_t`` and
  15. ``typedef``\ 'd so that the ``struct`` keyword need not be used.
  16. Library Version
  17. ===============
  18. The Jansson version is of the form *A.B.C*, where *A* is the major
  19. version, *B* is the minor version and *C* is the micro version. If the
  20. micro version is zero, it's omitted from the version string, i.e. the
  21. version string is just *A.B*.
  22. When a new release only fixes bugs and doesn't add new features or
  23. functionality, the micro version is incremented. When new features are
  24. added in a backwards compatible way, the minor version is incremented
  25. and the micro version is set to zero. When there are backwards
  26. incompatible changes, the major version is incremented and others are
  27. set to zero.
  28. The following preprocessor constants specify the current version of
  29. the library:
  30. ``JANSSON_MAJOR_VERSION``, ``JANSSON_MINOR_VERSION``, ``JANSSON_MICRO_VERSION``
  31. Integers specifying the major, minor and micro versions,
  32. respectively.
  33. ``JANSSON_VERSION``
  34. A string representation of the current version, e.g. ``"1.2.1"`` or
  35. ``"1.3"``.
  36. ``JANSSON_VERSION_HEX``
  37. A 3-byte hexadecimal representation of the version, e.g.
  38. ``0x010201`` for version 1.2.1 and ``0x010300`` for version 1.3.
  39. This is useful in numeric comparisons, e.g.::
  40. #if JANSSON_VERSION_HEX >= 0x010300
  41. /* Code specific to version 1.3 and above */
  42. #endif
  43. Value Representation
  44. ====================
  45. The JSON specification (:rfc:`4627`) defines the following data types:
  46. *object*, *array*, *string*, *number*, *boolean*, and *null*. JSON
  47. types are used dynamically; arrays and objects can hold any other data
  48. type, including themselves. For this reason, Jansson's type system is
  49. also dynamic in nature. There's one C type to represent all JSON
  50. values, and this structure knows the type of the JSON value it holds.
  51. .. type:: json_t
  52. This data structure is used throughout the library to represent all
  53. JSON values. It always contains the type of the JSON value it holds
  54. and the value's reference count. The rest depends on the type of the
  55. value.
  56. Objects of :type:`json_t` are always used through a pointer. There
  57. are APIs for querying the type, manipulating the reference count, and
  58. for constructing and manipulating values of different types.
  59. Unless noted otherwise, all API functions return an error value if an
  60. error occurs. Depending on the function's signature, the error value
  61. is either *NULL* or -1. Invalid arguments or invalid input are
  62. apparent sources for errors. Memory allocation and I/O operations may
  63. also cause errors.
  64. Type
  65. ----
  66. .. type:: enum json_type
  67. The type of a JSON value. The following members are defined:
  68. +--------------------+
  69. | ``JSON_OBJECT`` |
  70. +--------------------+
  71. | ``JSON_ARRAY`` |
  72. +--------------------+
  73. | ``JSON_STRING`` |
  74. +--------------------+
  75. | ``JSON_INTEGER`` |
  76. +--------------------+
  77. | ``JSON_REAL`` |
  78. +--------------------+
  79. | ``JSON_TRUE`` |
  80. +--------------------+
  81. | ``JSON_FALSE`` |
  82. +--------------------+
  83. | ``JSON_NULL`` |
  84. +--------------------+
  85. These correspond to JSON object, array, string, number, boolean and
  86. null. A number is represented by either a value of the type
  87. ``JSON_INTEGER`` or of the type ``JSON_REAL``. A true boolean value
  88. is represented by a value of the type ``JSON_TRUE`` and false by a
  89. value of the type ``JSON_FALSE``.
  90. .. function:: int json_typeof(const json_t *json)
  91. Return the type of the JSON value (a :type:`json_type` cast to
  92. :type:`int`). *json* MUST NOT be *NULL*. This function is actually
  93. implemented as a macro for speed.
  94. .. function:: json_is_object(const json_t *json)
  95. json_is_array(const json_t *json)
  96. json_is_string(const json_t *json)
  97. json_is_integer(const json_t *json)
  98. json_is_real(const json_t *json)
  99. json_is_true(const json_t *json)
  100. json_is_false(const json_t *json)
  101. json_is_null(const json_t *json)
  102. These functions (actually macros) return true (non-zero) for values
  103. of the given type, and false (zero) for values of other types and
  104. for *NULL*.
  105. .. function:: json_is_number(const json_t *json)
  106. Returns true for values of types ``JSON_INTEGER`` and
  107. ``JSON_REAL``, and false for other types and for *NULL*.
  108. .. function:: json_is_boolean(const json_t *json)
  109. Returns true for types ``JSON_TRUE`` and ``JSON_FALSE``, and false
  110. for values of other types and for *NULL*.
  111. .. function:: json_boolean_value(const json_t *json)
  112. Alias of :func:`json_is_true()`, i.e. returns 1 for ``JSON_TRUE``
  113. and 0 otherwise.
  114. .. versionadded:: 2.7
  115. .. _apiref-reference-count:
  116. Reference Count
  117. ---------------
  118. The reference count is used to track whether a value is still in use
  119. or not. When a value is created, it's reference count is set to 1. If
  120. a reference to a value is kept (e.g. a value is stored somewhere for
  121. later use), its reference count is incremented, and when the value is
  122. no longer needed, the reference count is decremented. When the
  123. reference count drops to zero, there are no references left, and the
  124. value can be destroyed.
  125. .. function:: json_t *json_incref(json_t *json)
  126. Increment the reference count of *json* if it's not *NULL*.
  127. Returns *json*.
  128. .. function:: void json_decref(json_t *json)
  129. Decrement the reference count of *json*. As soon as a call to
  130. :func:`json_decref()` drops the reference count to zero, the value
  131. is destroyed and it can no longer be used.
  132. Functions creating new JSON values set the reference count to 1. These
  133. functions are said to return a **new reference**. Other functions
  134. returning (existing) JSON values do not normally increase the
  135. reference count. These functions are said to return a **borrowed
  136. reference**. So, if the user will hold a reference to a value returned
  137. as a borrowed reference, he must call :func:`json_incref`. As soon as
  138. the value is no longer needed, :func:`json_decref` should be called
  139. to release the reference.
  140. Normally, all functions accepting a JSON value as an argument will
  141. manage the reference, i.e. increase and decrease the reference count
  142. as needed. However, some functions **steal** the reference, i.e. they
  143. have the same result as if the user called :func:`json_decref()` on
  144. the argument right after calling the function. These functions are
  145. suffixed with ``_new`` or have ``_new_`` somewhere in their name.
  146. For example, the following code creates a new JSON array and appends
  147. an integer to it::
  148. json_t *array, *integer;
  149. array = json_array();
  150. integer = json_integer(42);
  151. json_array_append(array, integer);
  152. json_decref(integer);
  153. Note how the caller has to release the reference to the integer value
  154. by calling :func:`json_decref()`. By using a reference stealing
  155. function :func:`json_array_append_new()` instead of
  156. :func:`json_array_append()`, the code becomes much simpler::
  157. json_t *array = json_array();
  158. json_array_append_new(array, json_integer(42));
  159. In this case, the user doesn't have to explicitly release the
  160. reference to the integer value, as :func:`json_array_append_new()`
  161. steals the reference when appending the value to the array.
  162. In the following sections it is clearly documented whether a function
  163. will return a new or borrowed reference or steal a reference to its
  164. argument.
  165. Circular References
  166. -------------------
  167. A circular reference is created when an object or an array is,
  168. directly or indirectly, inserted inside itself. The direct case is
  169. simple::
  170. json_t *obj = json_object();
  171. json_object_set(obj, "foo", obj);
  172. Jansson will refuse to do this, and :func:`json_object_set()` (and
  173. all the other such functions for objects and arrays) will return with
  174. an error status. The indirect case is the dangerous one::
  175. json_t *arr1 = json_array(), *arr2 = json_array();
  176. json_array_append(arr1, arr2);
  177. json_array_append(arr2, arr1);
  178. In this example, the array ``arr2`` is contained in the array
  179. ``arr1``, and vice versa. Jansson cannot check for this kind of
  180. indirect circular references without a performance hit, so it's up to
  181. the user to avoid them.
  182. If a circular reference is created, the memory consumed by the values
  183. cannot be freed by :func:`json_decref()`. The reference counts never
  184. drops to zero because the values are keeping the references to each
  185. other. Moreover, trying to encode the values with any of the encoding
  186. functions will fail. The encoder detects circular references and
  187. returns an error status.
  188. Scope Dereferencing
  189. -------------------
  190. .. versionadded:: 2.9
  191. It is possible to use the ``json_auto_t`` type to automatically
  192. dereference a value at the end of a scope. For example::
  193. void function(void) {
  194. json_auto_t *value = NULL;
  195. value = json_string("foo");
  196. /* json_decref(value) is automatically called. */
  197. }
  198. This feature is only available on GCC and Clang. So if your project
  199. has a portability requirement for other compilers, you should avoid
  200. this feature.
  201. Additionally, as always, care should be taken when passing values to
  202. functions that steal references.
  203. True, False and Null
  204. ====================
  205. These three values are implemented as singletons, so the returned
  206. pointers won't change between invocations of these functions.
  207. .. function:: json_t *json_true(void)
  208. .. refcounting:: new
  209. Returns the JSON true value.
  210. .. function:: json_t *json_false(void)
  211. .. refcounting:: new
  212. Returns the JSON false value.
  213. .. function:: json_t *json_boolean(val)
  214. .. refcounting:: new
  215. Returns JSON false if ``val`` is zero, and JSON true otherwise.
  216. This is a macro, and equivalent to ``val ? json_true() :
  217. json_false()``.
  218. .. versionadded:: 2.4
  219. .. function:: json_t *json_null(void)
  220. .. refcounting:: new
  221. Returns the JSON null value.
  222. String
  223. ======
  224. Jansson uses UTF-8 as the character encoding. All JSON strings must be
  225. valid UTF-8 (or ASCII, as it's a subset of UTF-8). All Unicode
  226. codepoints U+0000 through U+10FFFF are allowed, but you must use
  227. length-aware functions if you wish to embed null bytes in strings.
  228. .. function:: json_t *json_string(const char *value)
  229. .. refcounting:: new
  230. Returns a new JSON string, or *NULL* on error. *value* must be a
  231. valid null terminated UTF-8 encoded Unicode string.
  232. .. function:: json_t *json_stringn(const char *value, size_t len)
  233. .. refcounting:: new
  234. Like :func:`json_string`, but with explicit length, so *value* may
  235. contain null characters or not be null terminated.
  236. .. function:: json_t *json_string_nocheck(const char *value)
  237. .. refcounting:: new
  238. Like :func:`json_string`, but doesn't check that *value* is valid
  239. UTF-8. Use this function only if you are certain that this really
  240. is the case (e.g. you have already checked it by other means).
  241. .. function:: json_t *json_stringn_nocheck(const char *value, size_t len)
  242. .. refcounting:: new
  243. Like :func:`json_string_nocheck`, but with explicit length, so
  244. *value* may contain null characters or not be null terminated.
  245. .. function:: const char *json_string_value(const json_t *string)
  246. Returns the associated value of *string* as a null terminated UTF-8
  247. encoded string, or *NULL* if *string* is not a JSON string.
  248. The returned value is read-only and must not be modified or freed by
  249. the user. It is valid as long as *string* exists, i.e. as long as
  250. its reference count has not dropped to zero.
  251. .. function:: size_t json_string_length(const json_t *string)
  252. Returns the length of *string* in its UTF-8 presentation, or zero
  253. if *string* is not a JSON string.
  254. .. function:: int json_string_set(json_t *string, const char *value)
  255. Sets the associated value of *string* to *value*. *value* must be a
  256. valid UTF-8 encoded Unicode string. Returns 0 on success and -1 on
  257. error.
  258. .. function:: int json_string_setn(json_t *string, const char *value, size_t len)
  259. Like :func:`json_string_set`, but with explicit length, so *value*
  260. may contain null characters or not be null terminated.
  261. .. function:: int json_string_set_nocheck(json_t *string, const char *value)
  262. Like :func:`json_string_set`, but doesn't check that *value* is
  263. valid UTF-8. Use this function only if you are certain that this
  264. really is the case (e.g. you have already checked it by other
  265. means).
  266. .. function:: int json_string_setn_nocheck(json_t *string, const char *value, size_t len)
  267. Like :func:`json_string_set_nocheck`, but with explicit length,
  268. so *value* may contain null characters or not be null terminated.
  269. Number
  270. ======
  271. The JSON specification only contains one numeric type, "number". The C
  272. programming language has distinct types for integer and floating-point
  273. numbers, so for practical reasons Jansson also has distinct types for
  274. the two. They are called "integer" and "real", respectively. For more
  275. information, see :ref:`rfc-conformance`.
  276. .. type:: json_int_t
  277. This is the C type that is used to store JSON integer values. It
  278. represents the widest integer type available on your system. In
  279. practice it's just a typedef of ``long long`` if your compiler
  280. supports it, otherwise ``long``.
  281. Usually, you can safely use plain ``int`` in place of
  282. ``json_int_t``, and the implicit C integer conversion handles the
  283. rest. Only when you know that you need the full 64-bit range, you
  284. should use ``json_int_t`` explicitly.
  285. ``JSON_INTEGER_IS_LONG_LONG``
  286. This is a preprocessor variable that holds the value 1 if
  287. :type:`json_int_t` is ``long long``, and 0 if it's ``long``. It
  288. can be used as follows::
  289. #if JSON_INTEGER_IS_LONG_LONG
  290. /* Code specific for long long */
  291. #else
  292. /* Code specific for long */
  293. #endif
  294. ``JSON_INTEGER_FORMAT``
  295. This is a macro that expands to a :func:`printf()` conversion
  296. specifier that corresponds to :type:`json_int_t`, without the
  297. leading ``%`` sign, i.e. either ``"lld"`` or ``"ld"``. This macro
  298. is required because the actual type of :type:`json_int_t` can be
  299. either ``long`` or ``long long``, and :func:`printf()` requires
  300. different length modifiers for the two.
  301. Example::
  302. json_int_t x = 123123123;
  303. printf("x is %" JSON_INTEGER_FORMAT "\n", x);
  304. .. function:: json_t *json_integer(json_int_t value)
  305. .. refcounting:: new
  306. Returns a new JSON integer, or *NULL* on error.
  307. .. function:: json_int_t json_integer_value(const json_t *integer)
  308. Returns the associated value of *integer*, or 0 if *json* is not a
  309. JSON integer.
  310. .. function:: int json_integer_set(const json_t *integer, json_int_t value)
  311. Sets the associated value of *integer* to *value*. Returns 0 on
  312. success and -1 if *integer* is not a JSON integer.
  313. .. function:: json_t *json_real(double value)
  314. .. refcounting:: new
  315. Returns a new JSON real, or *NULL* on error.
  316. .. function:: double json_real_value(const json_t *real)
  317. Returns the associated value of *real*, or 0.0 if *real* is not a
  318. JSON real.
  319. .. function:: int json_real_set(const json_t *real, double value)
  320. Sets the associated value of *real* to *value*. Returns 0 on
  321. success and -1 if *real* is not a JSON real.
  322. .. function:: double json_number_value(const json_t *json)
  323. Returns the associated value of the JSON integer or JSON real
  324. *json*, cast to double regardless of the actual type. If *json* is
  325. neither JSON real nor JSON integer, 0.0 is returned.
  326. Array
  327. =====
  328. A JSON array is an ordered collection of other JSON values.
  329. .. function:: json_t *json_array(void)
  330. .. refcounting:: new
  331. Returns a new JSON array, or *NULL* on error. Initially, the array
  332. is empty.
  333. .. function:: size_t json_array_size(const json_t *array)
  334. Returns the number of elements in *array*, or 0 if *array* is NULL
  335. or not a JSON array.
  336. .. function:: json_t *json_array_get(const json_t *array, size_t index)
  337. .. refcounting:: borrow
  338. Returns the element in *array* at position *index*. The valid range
  339. for *index* is from 0 to the return value of
  340. :func:`json_array_size()` minus 1. If *array* is not a JSON array,
  341. if *array* is *NULL*, or if *index* is out of range, *NULL* is
  342. returned.
  343. .. function:: int json_array_set(json_t *array, size_t index, json_t *value)
  344. Replaces the element in *array* at position *index* with *value*.
  345. The valid range for *index* is from 0 to the return value of
  346. :func:`json_array_size()` minus 1. Returns 0 on success and -1 on
  347. error.
  348. .. function:: int json_array_set_new(json_t *array, size_t index, json_t *value)
  349. Like :func:`json_array_set()` but steals the reference to *value*.
  350. This is useful when *value* is newly created and not used after
  351. the call.
  352. .. function:: int json_array_append(json_t *array, json_t *value)
  353. Appends *value* to the end of *array*, growing the size of *array*
  354. by 1. Returns 0 on success and -1 on error.
  355. .. function:: int json_array_append_new(json_t *array, json_t *value)
  356. Like :func:`json_array_append()` but steals the reference to
  357. *value*. This is useful when *value* is newly created and not used
  358. after the call.
  359. .. function:: int json_array_insert(json_t *array, size_t index, json_t *value)
  360. Inserts *value* to *array* at position *index*, shifting the
  361. elements at *index* and after it one position towards the end of
  362. the array. Returns 0 on success and -1 on error.
  363. .. function:: int json_array_insert_new(json_t *array, size_t index, json_t *value)
  364. Like :func:`json_array_insert()` but steals the reference to
  365. *value*. This is useful when *value* is newly created and not used
  366. after the call.
  367. .. function:: int json_array_remove(json_t *array, size_t index)
  368. Removes the element in *array* at position *index*, shifting the
  369. elements after *index* one position towards the start of the array.
  370. Returns 0 on success and -1 on error. The reference count of the
  371. removed value is decremented.
  372. .. function:: int json_array_clear(json_t *array)
  373. Removes all elements from *array*. Returns 0 on success and -1 on
  374. error. The reference count of all removed values are decremented.
  375. .. function:: int json_array_extend(json_t *array, json_t *other_array)
  376. Appends all elements in *other_array* to the end of *array*.
  377. Returns 0 on success and -1 on error.
  378. .. function:: json_array_foreach(array, index, value)
  379. Iterate over every element of ``array``, running the block
  380. of code that follows each time with the proper values set to
  381. variables ``index`` and ``value``, of types :type:`size_t` and
  382. :type:`json_t *` respectively. Example::
  383. /* array is a JSON array */
  384. size_t index;
  385. json_t *value;
  386. json_array_foreach(array, index, value) {
  387. /* block of code that uses index and value */
  388. }
  389. The items are returned in increasing index order.
  390. This macro expands to an ordinary ``for`` statement upon
  391. preprocessing, so its performance is equivalent to that of
  392. hand-written code using the array access functions.
  393. The main advantage of this macro is that it abstracts
  394. away the complexity, and makes for more concise and readable code.
  395. .. versionadded:: 2.5
  396. Object
  397. ======
  398. A JSON object is a dictionary of key-value pairs, where the key is a
  399. Unicode string and the value is any JSON value.
  400. Even though null bytes are allowed in string values, they are not
  401. allowed in object keys.
  402. .. function:: json_t *json_object(void)
  403. .. refcounting:: new
  404. Returns a new JSON object, or *NULL* on error. Initially, the
  405. object is empty.
  406. .. function:: size_t json_object_size(const json_t *object)
  407. Returns the number of elements in *object*, or 0 if *object* is not
  408. a JSON object.
  409. .. function:: json_t *json_object_get(const json_t *object, const char *key)
  410. .. refcounting:: borrow
  411. Get a value corresponding to *key* from *object*. Returns *NULL* if
  412. *key* is not found and on error.
  413. .. function:: int json_object_set(json_t *object, const char *key, json_t *value)
  414. Set the value of *key* to *value* in *object*. *key* must be a
  415. valid null terminated UTF-8 encoded Unicode string. If there
  416. already is a value for *key*, it is replaced by the new value.
  417. Returns 0 on success and -1 on error.
  418. .. function:: int json_object_set_nocheck(json_t *object, const char *key, json_t *value)
  419. Like :func:`json_object_set`, but doesn't check that *key* is
  420. valid UTF-8. Use this function only if you are certain that this
  421. really is the case (e.g. you have already checked it by other
  422. means).
  423. .. function:: int json_object_set_new(json_t *object, const char *key, json_t *value)
  424. Like :func:`json_object_set()` but steals the reference to
  425. *value*. This is useful when *value* is newly created and not used
  426. after the call.
  427. .. function:: int json_object_set_new_nocheck(json_t *object, const char *key, json_t *value)
  428. Like :func:`json_object_set_new`, but doesn't check that *key* is
  429. valid UTF-8. Use this function only if you are certain that this
  430. really is the case (e.g. you have already checked it by other
  431. means).
  432. .. function:: int json_object_del(json_t *object, const char *key)
  433. Delete *key* from *object* if it exists. Returns 0 on success, or
  434. -1 if *key* was not found. The reference count of the removed value
  435. is decremented.
  436. .. function:: int json_object_clear(json_t *object)
  437. Remove all elements from *object*. Returns 0 on success and -1 if
  438. *object* is not a JSON object. The reference count of all removed
  439. values are decremented.
  440. .. function:: int json_object_update(json_t *object, json_t *other)
  441. Update *object* with the key-value pairs from *other*, overwriting
  442. existing keys. Returns 0 on success or -1 on error.
  443. .. function:: int json_object_update_existing(json_t *object, json_t *other)
  444. Like :func:`json_object_update()`, but only the values of existing
  445. keys are updated. No new keys are created. Returns 0 on success or
  446. -1 on error.
  447. .. versionadded:: 2.3
  448. .. function:: int json_object_update_missing(json_t *object, json_t *other)
  449. Like :func:`json_object_update()`, but only new keys are created.
  450. The value of any existing key is not changed. Returns 0 on success
  451. or -1 on error.
  452. .. versionadded:: 2.3
  453. .. function:: json_object_foreach(object, key, value)
  454. Iterate over every key-value pair of ``object``, running the block
  455. of code that follows each time with the proper values set to
  456. variables ``key`` and ``value``, of types :type:`const char *` and
  457. :type:`json_t *` respectively. Example::
  458. /* obj is a JSON object */
  459. const char *key;
  460. json_t *value;
  461. json_object_foreach(obj, key, value) {
  462. /* block of code that uses key and value */
  463. }
  464. The items are returned in the order they were inserted to the
  465. object.
  466. **Note:** It's not safe to call ``json_object_del(object, key)``
  467. during iteration. If you need to, use
  468. :func:`json_object_foreach_safe` instead.
  469. This macro expands to an ordinary ``for`` statement upon
  470. preprocessing, so its performance is equivalent to that of
  471. hand-written iteration code using the object iteration protocol
  472. (see below). The main advantage of this macro is that it abstracts
  473. away the complexity behind iteration, and makes for more concise and
  474. readable code.
  475. .. versionadded:: 2.3
  476. .. function:: json_object_foreach_safe(object, tmp, key, value)
  477. Like :func:`json_object_foreach()`, but it's safe to call
  478. ``json_object_del(object, key)`` during iteration. You need to pass
  479. an extra ``void *`` parameter ``tmp`` that is used for temporary storage.
  480. .. versionadded:: 2.8
  481. The following functions can be used to iterate through all key-value
  482. pairs in an object. The items are returned in the order they were
  483. inserted to the object.
  484. .. function:: void *json_object_iter(json_t *object)
  485. Returns an opaque iterator which can be used to iterate over all
  486. key-value pairs in *object*, or *NULL* if *object* is empty.
  487. .. function:: void *json_object_iter_at(json_t *object, const char *key)
  488. Like :func:`json_object_iter()`, but returns an iterator to the
  489. key-value pair in *object* whose key is equal to *key*, or NULL if
  490. *key* is not found in *object*. Iterating forward to the end of
  491. *object* only yields all key-value pairs of the object if *key*
  492. happens to be the first key in the underlying hash table.
  493. .. function:: void *json_object_iter_next(json_t *object, void *iter)
  494. Returns an iterator pointing to the next key-value pair in *object*
  495. after *iter*, or *NULL* if the whole object has been iterated
  496. through.
  497. .. function:: const char *json_object_iter_key(void *iter)
  498. Extract the associated key from *iter*.
  499. .. function:: json_t *json_object_iter_value(void *iter)
  500. .. refcounting:: borrow
  501. Extract the associated value from *iter*.
  502. .. function:: int json_object_iter_set(json_t *object, void *iter, json_t *value)
  503. Set the value of the key-value pair in *object*, that is pointed to
  504. by *iter*, to *value*.
  505. .. function:: int json_object_iter_set_new(json_t *object, void *iter, json_t *value)
  506. Like :func:`json_object_iter_set()`, but steals the reference to
  507. *value*. This is useful when *value* is newly created and not used
  508. after the call.
  509. .. function:: void *json_object_key_to_iter(const char *key)
  510. Like :func:`json_object_iter_at()`, but much faster. Only works for
  511. values returned by :func:`json_object_iter_key()`. Using other keys
  512. will lead to segfaults. This function is used internally to
  513. implement :func:`json_object_foreach`. Example::
  514. /* obj is a JSON object */
  515. const char *key;
  516. json_t *value;
  517. void *iter = json_object_iter(obj);
  518. while(iter)
  519. {
  520. key = json_object_iter_key(iter);
  521. value = json_object_iter_value(iter);
  522. /* use key and value ... */
  523. iter = json_object_iter_next(obj, iter);
  524. }
  525. .. versionadded:: 2.3
  526. .. function:: void json_object_seed(size_t seed)
  527. Seed the hash function used in Jansson's hashtable implementation.
  528. The seed is used to randomize the hash function so that an
  529. attacker cannot control its output.
  530. If *seed* is 0, Jansson generates the seed itself by reading
  531. random data from the operating system's entropy sources. If no
  532. entropy sources are available, falls back to using a combination
  533. of the current timestamp (with microsecond precision if possible)
  534. and the process ID.
  535. If called at all, this function must be called before any calls to
  536. :func:`json_object()`, either explicit or implicit. If this
  537. function is not called by the user, the first call to
  538. :func:`json_object()` (either explicit or implicit) seeds the hash
  539. function. See :ref:`portability-thread-safety` for notes on thread
  540. safety.
  541. If repeatable results are required, for e.g. unit tests, the hash
  542. function can be "unrandomized" by calling :func:`json_object_seed`
  543. with a constant value on program startup, e.g.
  544. ``json_object_seed(1)``.
  545. .. versionadded:: 2.6
  546. Error reporting
  547. ===============
  548. Jansson uses a single struct type to pass error information to the
  549. user. See sections :ref:`apiref-decoding`, :ref:`apiref-pack` and
  550. :ref:`apiref-unpack` for functions that pass error information using
  551. this struct.
  552. .. type:: json_error_t
  553. .. member:: char text[]
  554. The error message (in UTF-8), or an empty string if a message is
  555. not available.
  556. .. member:: char source[]
  557. Source of the error. This can be (a part of) the file name or a
  558. special identifier in angle brackets (e.g. ``<string>``).
  559. .. member:: int line
  560. The line number on which the error occurred.
  561. .. member:: int column
  562. The column on which the error occurred. Note that this is the
  563. *character column*, not the byte column, i.e. a multibyte UTF-8
  564. character counts as one column.
  565. .. member:: int position
  566. The position in bytes from the start of the input. This is
  567. useful for debugging Unicode encoding problems.
  568. The normal use of :type:`json_error_t` is to allocate it on the stack,
  569. and pass a pointer to a function. Example::
  570. int main() {
  571. json_t *json;
  572. json_error_t error;
  573. json = json_load_file("/path/to/file.json", 0, &error);
  574. if(!json) {
  575. /* the error variable contains error information */
  576. }
  577. ...
  578. }
  579. Also note that if the call succeeded (``json != NULL`` in the above
  580. example), the contents of ``error`` are generally left unspecified.
  581. The decoding functions write to the ``position`` member also on
  582. success. See :ref:`apiref-decoding` for more info.
  583. All functions also accept *NULL* as the :type:`json_error_t` pointer,
  584. in which case no error information is returned to the caller.
  585. Encoding
  586. ========
  587. This sections describes the functions that can be used to encode
  588. values to JSON. By default, only objects and arrays can be encoded
  589. directly, since they are the only valid *root* values of a JSON text.
  590. To encode any JSON value, use the ``JSON_ENCODE_ANY`` flag (see
  591. below).
  592. By default, the output has no newlines, and spaces are used between
  593. array and object elements for a readable output. This behavior can be
  594. altered by using the ``JSON_INDENT`` and ``JSON_COMPACT`` flags
  595. described below. A newline is never appended to the end of the encoded
  596. JSON data.
  597. Each function takes a *flags* parameter that controls some aspects of
  598. how the data is encoded. Its default value is 0. The following macros
  599. can be ORed together to obtain *flags*.
  600. ``JSON_INDENT(n)``
  601. Pretty-print the result, using newlines between array and object
  602. items, and indenting with *n* spaces. The valid range for *n* is
  603. between 0 and 31 (inclusive), other values result in an undefined
  604. output. If ``JSON_INDENT`` is not used or *n* is 0, no newlines are
  605. inserted between array and object items.
  606. The ``JSON_MAX_INDENT`` constant defines the maximum indentation
  607. that can be used, and its value is 31.
  608. .. versionchanged:: 2.7
  609. Added ``JSON_MAX_INDENT``.
  610. ``JSON_COMPACT``
  611. This flag enables a compact representation, i.e. sets the separator
  612. between array and object items to ``","`` and between object keys
  613. and values to ``":"``. Without this flag, the corresponding
  614. separators are ``", "`` and ``": "`` for more readable output.
  615. ``JSON_ENSURE_ASCII``
  616. If this flag is used, the output is guaranteed to consist only of
  617. ASCII characters. This is achieved by escaping all Unicode
  618. characters outside the ASCII range.
  619. ``JSON_SORT_KEYS``
  620. If this flag is used, all the objects in output are sorted by key.
  621. This is useful e.g. if two JSON texts are diffed or visually
  622. compared.
  623. ``JSON_PRESERVE_ORDER``
  624. **Deprecated since version 2.8:** Order of object keys
  625. is always preserved.
  626. Prior to version 2.8: If this flag is used, object keys in the
  627. output are sorted into the same order in which they were first
  628. inserted to the object. For example, decoding a JSON text and then
  629. encoding with this flag preserves the order of object keys.
  630. ``JSON_ENCODE_ANY``
  631. Specifying this flag makes it possible to encode any JSON value on
  632. its own. Without it, only objects and arrays can be passed as the
  633. *json* value to the encoding functions.
  634. **Note:** Encoding any value may be useful in some scenarios, but
  635. it's generally discouraged as it violates strict compatibility with
  636. :rfc:`4627`. If you use this flag, don't expect interoperability
  637. with other JSON systems.
  638. .. versionadded:: 2.1
  639. ``JSON_ESCAPE_SLASH``
  640. Escape the ``/`` characters in strings with ``\/``.
  641. .. versionadded:: 2.4
  642. ``JSON_REAL_PRECISION(n)``
  643. Output all real numbers with at most *n* digits of precision. The
  644. valid range for *n* is between 0 and 31 (inclusive), and other
  645. values result in an undefined behavior.
  646. By default, the precision is 17, to correctly and losslessly encode
  647. all IEEE 754 double precision floating point numbers.
  648. .. versionadded:: 2.7
  649. These functions output UTF-8:
  650. .. function:: char *json_dumps(const json_t *json, size_t flags)
  651. Returns the JSON representation of *json* as a string, or *NULL* on
  652. error. *flags* is described above. The return value must be freed
  653. by the caller using :func:`free()`.
  654. .. function:: int json_dumpf(const json_t *json, FILE *output, size_t flags)
  655. Write the JSON representation of *json* to the stream *output*.
  656. *flags* is described above. Returns 0 on success and -1 on error.
  657. If an error occurs, something may have already been written to
  658. *output*. In this case, the output is undefined and most likely not
  659. valid JSON.
  660. .. function:: int json_dump_file(const json_t *json, const char *path, size_t flags)
  661. Write the JSON representation of *json* to the file *path*. If
  662. *path* already exists, it is overwritten. *flags* is described
  663. above. Returns 0 on success and -1 on error.
  664. .. type:: json_dump_callback_t
  665. A typedef for a function that's called by
  666. :func:`json_dump_callback()`::
  667. typedef int (*json_dump_callback_t)(const char *buffer, size_t size, void *data);
  668. *buffer* points to a buffer containing a chunk of output, *size* is
  669. the length of the buffer, and *data* is the corresponding
  670. :func:`json_dump_callback()` argument passed through.
  671. On error, the function should return -1 to stop the encoding
  672. process. On success, it should return 0.
  673. .. versionadded:: 2.2
  674. .. function:: int json_dump_callback(const json_t *json, json_dump_callback_t callback, void *data, size_t flags)
  675. Call *callback* repeatedly, passing a chunk of the JSON
  676. representation of *json* each time. *flags* is described above.
  677. Returns 0 on success and -1 on error.
  678. .. versionadded:: 2.2
  679. .. _apiref-decoding:
  680. Decoding
  681. ========
  682. This sections describes the functions that can be used to decode JSON
  683. text to the Jansson representation of JSON data. The JSON
  684. specification requires that a JSON text is either a serialized array
  685. or object, and this requirement is also enforced with the following
  686. functions. In other words, the top level value in the JSON text being
  687. decoded must be either array or object. To decode any JSON value, use
  688. the ``JSON_DECODE_ANY`` flag (see below).
  689. See :ref:`rfc-conformance` for a discussion on Jansson's conformance
  690. to the JSON specification. It explains many design decisions that
  691. affect especially the behavior of the decoder.
  692. Each function takes a *flags* parameter that can be used to control
  693. the behavior of the decoder. Its default value is 0. The following
  694. macros can be ORed together to obtain *flags*.
  695. ``JSON_REJECT_DUPLICATES``
  696. Issue a decoding error if any JSON object in the input text
  697. contains duplicate keys. Without this flag, the value of the last
  698. occurrence of each key ends up in the result. Key equivalence is
  699. checked byte-by-byte, without special Unicode comparison
  700. algorithms.
  701. .. versionadded:: 2.1
  702. ``JSON_DECODE_ANY``
  703. By default, the decoder expects an array or object as the input.
  704. With this flag enabled, the decoder accepts any valid JSON value.
  705. **Note:** Decoding any value may be useful in some scenarios, but
  706. it's generally discouraged as it violates strict compatibility with
  707. :rfc:`4627`. If you use this flag, don't expect interoperability
  708. with other JSON systems.
  709. .. versionadded:: 2.3
  710. ``JSON_DISABLE_EOF_CHECK``
  711. By default, the decoder expects that its whole input constitutes a
  712. valid JSON text, and issues an error if there's extra data after
  713. the otherwise valid JSON input. With this flag enabled, the decoder
  714. stops after decoding a valid JSON array or object, and thus allows
  715. extra data after the JSON text.
  716. Normally, reading will stop when the last ``]`` or ``}`` in the
  717. JSON input is encountered. If both ``JSON_DISABLE_EOF_CHECK`` and
  718. ``JSON_DECODE_ANY`` flags are used, the decoder may read one extra
  719. UTF-8 code unit (up to 4 bytes of input). For example, decoding
  720. ``4true`` correctly decodes the integer 4, but also reads the
  721. ``t``. For this reason, if reading multiple consecutive values that
  722. are not arrays or objects, they should be separated by at least one
  723. whitespace character.
  724. .. versionadded:: 2.1
  725. ``JSON_DECODE_INT_AS_REAL``
  726. JSON defines only one number type. Jansson distinguishes between
  727. ints and reals. For more information see :ref:`real-vs-integer`.
  728. With this flag enabled the decoder interprets all numbers as real
  729. values. Integers that do not have an exact double representation
  730. will silently result in a loss of precision. Integers that cause
  731. a double overflow will cause an error.
  732. .. versionadded:: 2.5
  733. ``JSON_ALLOW_NUL``
  734. Allow ``\u0000`` escape inside string values. This is a safety
  735. measure; If you know your input can contain null bytes, use this
  736. flag. If you don't use this flag, you don't have to worry about null
  737. bytes inside strings unless you explicitly create themselves by
  738. using e.g. :func:`json_stringn()` or ``s#`` format specifier for
  739. :func:`json_pack()`.
  740. Object keys cannot have embedded null bytes even if this flag is
  741. used.
  742. .. versionadded:: 2.6
  743. Each function also takes an optional :type:`json_error_t` parameter
  744. that is filled with error information if decoding fails. It's also
  745. updated on success; the number of bytes of input read is written to
  746. its ``position`` field. This is especially useful when using
  747. ``JSON_DISABLE_EOF_CHECK`` to read multiple consecutive JSON texts.
  748. .. versionadded:: 2.3
  749. Number of bytes of input read is written to the ``position`` field
  750. of the :type:`json_error_t` structure.
  751. If no error or position information is needed, you can pass *NULL*.
  752. .. function:: json_t *json_loads(const char *input, size_t flags, json_error_t *error)
  753. .. refcounting:: new
  754. Decodes the JSON string *input* and returns the array or object it
  755. contains, or *NULL* on error, in which case *error* is filled with
  756. information about the error. *flags* is described above.
  757. .. function:: json_t *json_loadb(const char *buffer, size_t buflen, size_t flags, json_error_t *error)
  758. .. refcounting:: new
  759. Decodes the JSON string *buffer*, whose length is *buflen*, and
  760. returns the array or object it contains, or *NULL* on error, in
  761. which case *error* is filled with information about the error. This
  762. is similar to :func:`json_loads()` except that the string doesn't
  763. need to be null-terminated. *flags* is described above.
  764. .. versionadded:: 2.1
  765. .. function:: json_t *json_loadf(FILE *input, size_t flags, json_error_t *error)
  766. .. refcounting:: new
  767. Decodes the JSON text in stream *input* and returns the array or
  768. object it contains, or *NULL* on error, in which case *error* is
  769. filled with information about the error. *flags* is described
  770. above.
  771. This function will start reading the input from whatever position
  772. the input file was, without attempting to seek first. If an error
  773. occurs, the file position will be left indeterminate. On success,
  774. the file position will be at EOF, unless ``JSON_DISABLE_EOF_CHECK``
  775. flag was used. In this case, the file position will be at the first
  776. character after the last ``]`` or ``}`` in the JSON input. This
  777. allows calling :func:`json_loadf()` on the same ``FILE`` object
  778. multiple times, if the input consists of consecutive JSON texts,
  779. possibly separated by whitespace.
  780. .. function:: json_t *json_load_file(const char *path, size_t flags, json_error_t *error)
  781. .. refcounting:: new
  782. Decodes the JSON text in file *path* and returns the array or
  783. object it contains, or *NULL* on error, in which case *error* is
  784. filled with information about the error. *flags* is described
  785. above.
  786. .. type:: json_load_callback_t
  787. A typedef for a function that's called by
  788. :func:`json_load_callback()` to read a chunk of input data::
  789. typedef size_t (*json_load_callback_t)(void *buffer, size_t buflen, void *data);
  790. *buffer* points to a buffer of *buflen* bytes, and *data* is the
  791. corresponding :func:`json_load_callback()` argument passed through.
  792. On success, the function should return the number of bytes read; a
  793. returned value of 0 indicates that no data was read and that the
  794. end of file has been reached. On error, the function should return
  795. ``(size_t)-1`` to abort the decoding process.
  796. .. versionadded:: 2.4
  797. .. function:: json_t *json_load_callback(json_load_callback_t callback, void *data, size_t flags, json_error_t *error)
  798. .. refcounting:: new
  799. Decodes the JSON text produced by repeated calls to *callback*, and
  800. returns the array or object it contains, or *NULL* on error, in
  801. which case *error* is filled with information about the error.
  802. *data* is passed through to *callback* on each call. *flags* is
  803. described above.
  804. .. versionadded:: 2.4
  805. .. _apiref-pack:
  806. Building Values
  807. ===============
  808. This section describes functions that help to create, or *pack*,
  809. complex JSON values, especially nested objects and arrays. Value
  810. building is based on a *format string* that is used to tell the
  811. functions about the expected arguments.
  812. For example, the format string ``"i"`` specifies a single integer
  813. value, while the format string ``"[ssb]"`` or the equivalent ``"[s, s,
  814. b]"`` specifies an array value with two strings and a boolean as its
  815. items::
  816. /* Create the JSON integer 42 */
  817. json_pack("i", 42);
  818. /* Create the JSON array ["foo", "bar", true] */
  819. json_pack("[ssb]", "foo", "bar", 1);
  820. Here's the full list of format specifiers. The type in parentheses
  821. denotes the resulting JSON type, and the type in brackets (if any)
  822. denotes the C type that is expected as the corresponding argument or
  823. arguments.
  824. ``s`` (string) [const char \*]
  825. Convert a null terminated UTF-8 string to a JSON string.
  826. ``s?`` (string) [const char \*]
  827. Like ``s``, but if the argument is *NULL*, output a JSON null
  828. value.
  829. .. versionadded:: 2.8
  830. ``s#`` (string) [const char \*, int]
  831. Convert a UTF-8 buffer of a given length to a JSON string.
  832. .. versionadded:: 2.5
  833. ``s%`` (string) [const char \*, size_t]
  834. Like ``s#`` but the length argument is of type :type:`size_t`.
  835. .. versionadded:: 2.6
  836. ``+`` [const char \*]
  837. Like ``s``, but concatenate to the previous string. Only valid
  838. after ``s``, ``s#``, ``+`` or ``+#``.
  839. .. versionadded:: 2.5
  840. ``+#`` [const char \*, int]
  841. Like ``s#``, but concatenate to the previous string. Only valid
  842. after ``s``, ``s#``, ``+`` or ``+#``.
  843. .. versionadded:: 2.5
  844. ``+%`` (string) [const char \*, size_t]
  845. Like ``+#`` but the length argument is of type :type:`size_t`.
  846. .. versionadded:: 2.6
  847. ``n`` (null)
  848. Output a JSON null value. No argument is consumed.
  849. ``b`` (boolean) [int]
  850. Convert a C :type:`int` to JSON boolean value. Zero is converted
  851. to ``false`` and non-zero to ``true``.
  852. ``i`` (integer) [int]
  853. Convert a C :type:`int` to JSON integer.
  854. ``I`` (integer) [json_int_t]
  855. Convert a C :type:`json_int_t` to JSON integer.
  856. ``f`` (real) [double]
  857. Convert a C :type:`double` to JSON real.
  858. ``o`` (any value) [json_t \*]
  859. Output any given JSON value as-is. If the value is added to an
  860. array or object, the reference to the value passed to ``o`` is
  861. stolen by the container.
  862. ``O`` (any value) [json_t \*]
  863. Like ``o``, but the argument's reference count is incremented.
  864. This is useful if you pack into an array or object and want to
  865. keep the reference for the JSON value consumed by ``O`` to
  866. yourself.
  867. ``o?``, ``O?`` (any value) [json_t \*]
  868. Like ``o`` and ``O?``, respectively, but if the argument is
  869. *NULL*, output a JSON null value.
  870. .. versionadded:: 2.8
  871. ``[fmt]`` (array)
  872. Build an array with contents from the inner format string. ``fmt``
  873. may contain objects and arrays, i.e. recursive value building is
  874. supported.
  875. ``{fmt}`` (object)
  876. Build an object with contents from the inner format string
  877. ``fmt``. The first, third, etc. format specifier represent a key,
  878. and must be a string (see ``s``, ``s#``, ``+`` and ``+#`` above),
  879. as object keys are always strings. The second, fourth, etc. format
  880. specifier represent a value. Any value may be an object or array,
  881. i.e. recursive value building is supported.
  882. Whitespace, ``:`` and ``,`` are ignored.
  883. .. function:: json_t *json_pack(const char *fmt, ...)
  884. .. refcounting:: new
  885. Build a new JSON value according to the format string *fmt*. For
  886. each format specifier (except for ``{}[]n``), one or more arguments
  887. are consumed and used to build the corresponding value. Returns
  888. *NULL* on error.
  889. .. function:: json_t *json_pack_ex(json_error_t *error, size_t flags, const char *fmt, ...)
  890. json_t *json_vpack_ex(json_error_t *error, size_t flags, const char *fmt, va_list ap)
  891. .. refcounting:: new
  892. Like :func:`json_pack()`, but an in the case of an error, an error
  893. message is written to *error*, if it's not *NULL*. The *flags*
  894. parameter is currently unused and should be set to 0.
  895. As only the errors in format string (and out-of-memory errors) can
  896. be caught by the packer, these two functions are most likely only
  897. useful for debugging format strings.
  898. More examples::
  899. /* Build an empty JSON object */
  900. json_pack("{}");
  901. /* Build the JSON object {"foo": 42, "bar": 7} */
  902. json_pack("{sisi}", "foo", 42, "bar", 7);
  903. /* Like above, ':', ',' and whitespace are ignored */
  904. json_pack("{s:i, s:i}", "foo", 42, "bar", 7);
  905. /* Build the JSON array [[1, 2], {"cool": true}] */
  906. json_pack("[[i,i],{s:b}]", 1, 2, "cool", 1);
  907. /* Build a string from a non-null terminated buffer */
  908. char buffer[4] = {'t', 'e', 's', 't'};
  909. json_pack("s#", buffer, 4);
  910. /* Concatenate strings together to build the JSON string "foobarbaz" */
  911. json_pack("s++", "foo", "bar", "baz");
  912. .. _apiref-unpack:
  913. Parsing and Validating Values
  914. =============================
  915. This section describes functions that help to validate complex values
  916. and extract, or *unpack*, data from them. Like :ref:`building values
  917. <apiref-pack>`, this is also based on format strings.
  918. While a JSON value is unpacked, the type specified in the format
  919. string is checked to match that of the JSON value. This is the
  920. validation part of the process. In addition to this, the unpacking
  921. functions can also check that all items of arrays and objects are
  922. unpacked. This check be enabled with the format specifier ``!`` or by
  923. using the flag ``JSON_STRICT``. See below for details.
  924. Here's the full list of format specifiers. The type in parentheses
  925. denotes the JSON type, and the type in brackets (if any) denotes the C
  926. type whose address should be passed.
  927. ``s`` (string) [const char \*]
  928. Convert a JSON string to a pointer to a null terminated UTF-8
  929. string. The resulting string is extracted by using
  930. :func:`json_string_value()` internally, so it exists as long as
  931. there are still references to the corresponding JSON string.
  932. ``s%`` (string) [const char \*, size_t \*]
  933. Convert a JSON string to a pointer to a null terminated UTF-8
  934. string and its length.
  935. .. versionadded:: 2.6
  936. ``n`` (null)
  937. Expect a JSON null value. Nothing is extracted.
  938. ``b`` (boolean) [int]
  939. Convert a JSON boolean value to a C :type:`int`, so that ``true``
  940. is converted to 1 and ``false`` to 0.
  941. ``i`` (integer) [int]
  942. Convert a JSON integer to C :type:`int`.
  943. ``I`` (integer) [json_int_t]
  944. Convert a JSON integer to C :type:`json_int_t`.
  945. ``f`` (real) [double]
  946. Convert a JSON real to C :type:`double`.
  947. ``F`` (integer or real) [double]
  948. Convert a JSON number (integer or real) to C :type:`double`.
  949. ``o`` (any value) [json_t \*]
  950. Store a JSON value with no conversion to a :type:`json_t` pointer.
  951. ``O`` (any value) [json_t \*]
  952. Like ``O``, but the JSON value's reference count is incremented.
  953. ``[fmt]`` (array)
  954. Convert each item in the JSON array according to the inner format
  955. string. ``fmt`` may contain objects and arrays, i.e. recursive
  956. value extraction is supported.
  957. ``{fmt}`` (object)
  958. Convert each item in the JSON object according to the inner format
  959. string ``fmt``. The first, third, etc. format specifier represent
  960. a key, and must be ``s``. The corresponding argument to unpack
  961. functions is read as the object key. The second fourth, etc.
  962. format specifier represent a value and is written to the address
  963. given as the corresponding argument. **Note** that every other
  964. argument is read from and every other is written to.
  965. ``fmt`` may contain objects and arrays as values, i.e. recursive
  966. value extraction is supported.
  967. .. versionadded:: 2.3
  968. Any ``s`` representing a key may be suffixed with a ``?`` to
  969. make the key optional. If the key is not found, nothing is
  970. extracted. See below for an example.
  971. ``!``
  972. This special format specifier is used to enable the check that
  973. all object and array items are accessed, on a per-value basis. It
  974. must appear inside an array or object as the last format specifier
  975. before the closing bracket or brace. To enable the check globally,
  976. use the ``JSON_STRICT`` unpacking flag.
  977. ``*``
  978. This special format specifier is the opposite of ``!``. If the
  979. ``JSON_STRICT`` flag is used, ``*`` can be used to disable the
  980. strict check on a per-value basis. It must appear inside an array
  981. or object as the last format specifier before the closing bracket
  982. or brace.
  983. Whitespace, ``:`` and ``,`` are ignored.
  984. .. function:: int json_unpack(json_t *root, const char *fmt, ...)
  985. Validate and unpack the JSON value *root* according to the format
  986. string *fmt*. Returns 0 on success and -1 on failure.
  987. .. function:: int json_unpack_ex(json_t *root, json_error_t *error, size_t flags, const char *fmt, ...)
  988. int json_vunpack_ex(json_t *root, json_error_t *error, size_t flags, const char *fmt, va_list ap)
  989. Validate and unpack the JSON value *root* according to the format
  990. string *fmt*. If an error occurs and *error* is not *NULL*, write
  991. error information to *error*. *flags* can be used to control the
  992. behaviour of the unpacker, see below for the flags. Returns 0 on
  993. success and -1 on failure.
  994. .. note::
  995. The first argument of all unpack functions is ``json_t *root``
  996. instead of ``const json_t *root``, because the use of ``O`` format
  997. specifier causes the reference count of ``root``, or some value
  998. reachable from ``root``, to be increased. Furthermore, the ``o``
  999. format specifier may be used to extract a value as-is, which allows
  1000. modifying the structure or contents of a value reachable from
  1001. ``root``.
  1002. If the ``O`` and ``o`` format specifiers are not used, it's
  1003. perfectly safe to cast a ``const json_t *`` variable to plain
  1004. ``json_t *`` when used with these functions.
  1005. The following unpacking flags are available:
  1006. ``JSON_STRICT``
  1007. Enable the extra validation step checking that all object and
  1008. array items are unpacked. This is equivalent to appending the
  1009. format specifier ``!`` to the end of every array and object in the
  1010. format string.
  1011. ``JSON_VALIDATE_ONLY``
  1012. Don't extract any data, just validate the JSON value against the
  1013. given format string. Note that object keys must still be specified
  1014. after the format string.
  1015. Examples::
  1016. /* root is the JSON integer 42 */
  1017. int myint;
  1018. json_unpack(root, "i", &myint);
  1019. assert(myint == 42);
  1020. /* root is the JSON object {"foo": "bar", "quux": true} */
  1021. const char *str;
  1022. int boolean;
  1023. json_unpack(root, "{s:s, s:b}", "foo", &str, "quux", &boolean);
  1024. assert(strcmp(str, "bar") == 0 && boolean == 1);
  1025. /* root is the JSON array [[1, 2], {"baz": null} */
  1026. json_error_t error;
  1027. json_unpack_ex(root, &error, JSON_VALIDATE_ONLY, "[[i,i], {s:n}]", "baz");
  1028. /* returns 0 for validation success, nothing is extracted */
  1029. /* root is the JSON array [1, 2, 3, 4, 5] */
  1030. int myint1, myint2;
  1031. json_unpack(root, "[ii!]", &myint1, &myint2);
  1032. /* returns -1 for failed validation */
  1033. /* root is an empty JSON object */
  1034. int myint = 0, myint2 = 0, myint3 = 0;
  1035. json_unpack(root, "{s?i, s?[ii]}",
  1036. "foo", &myint1,
  1037. "bar", &myint2, &myint3);
  1038. /* myint1, myint2 or myint3 is no touched as "foo" and "bar" don't exist */
  1039. Equality
  1040. ========
  1041. Testing for equality of two JSON values cannot, in general, be
  1042. achieved using the ``==`` operator. Equality in the terms of the
  1043. ``==`` operator states that the two :type:`json_t` pointers point to
  1044. exactly the same JSON value. However, two JSON values can be equal not
  1045. only if they are exactly the same value, but also if they have equal
  1046. "contents":
  1047. * Two integer or real values are equal if their contained numeric
  1048. values are equal. An integer value is never equal to a real value,
  1049. though.
  1050. * Two strings are equal if their contained UTF-8 strings are equal,
  1051. byte by byte. Unicode comparison algorithms are not implemented.
  1052. * Two arrays are equal if they have the same number of elements and
  1053. each element in the first array is equal to the corresponding
  1054. element in the second array.
  1055. * Two objects are equal if they have exactly the same keys and the
  1056. value for each key in the first object is equal to the value of the
  1057. corresponding key in the second object.
  1058. * Two true, false or null values have no "contents", so they are equal
  1059. if their types are equal. (Because these values are singletons,
  1060. their equality can actually be tested with ``==``.)
  1061. .. function:: int json_equal(json_t *value1, json_t *value2)
  1062. Returns 1 if *value1* and *value2* are equal, as defined above.
  1063. Returns 0 if they are unequal or one or both of the pointers are
  1064. *NULL*.
  1065. Copying
  1066. =======
  1067. Because of reference counting, passing JSON values around doesn't
  1068. require copying them. But sometimes a fresh copy of a JSON value is
  1069. needed. For example, if you need to modify an array, but still want to
  1070. use the original afterwards, you should take a copy of it first.
  1071. Jansson supports two kinds of copying: shallow and deep. There is a
  1072. difference between these methods only for arrays and objects. Shallow
  1073. copying only copies the first level value (array or object) and uses
  1074. the same child values in the copied value. Deep copying makes a fresh
  1075. copy of the child values, too. Moreover, all the child values are deep
  1076. copied in a recursive fashion.
  1077. Copying objects preserves the insertion order of keys.
  1078. .. function:: json_t *json_copy(json_t *value)
  1079. .. refcounting:: new
  1080. Returns a shallow copy of *value*, or *NULL* on error.
  1081. .. function:: json_t *json_deep_copy(const json_t *value)
  1082. .. refcounting:: new
  1083. Returns a deep copy of *value*, or *NULL* on error.
  1084. .. _apiref-custom-memory-allocation:
  1085. Custom Memory Allocation
  1086. ========================
  1087. By default, Jansson uses :func:`malloc()` and :func:`free()` for
  1088. memory allocation. These functions can be overridden if custom
  1089. behavior is needed.
  1090. .. type:: json_malloc_t
  1091. A typedef for a function pointer with :func:`malloc()`'s
  1092. signature::
  1093. typedef void *(*json_malloc_t)(size_t);
  1094. .. type:: json_free_t
  1095. A typedef for a function pointer with :func:`free()`'s
  1096. signature::
  1097. typedef void (*json_free_t)(void *);
  1098. .. function:: void json_set_alloc_funcs(json_malloc_t malloc_fn, json_free_t free_fn)
  1099. Use *malloc_fn* instead of :func:`malloc()` and *free_fn* instead
  1100. of :func:`free()`. This function has to be called before any other
  1101. Jansson's API functions to ensure that all memory operations use
  1102. the same functions.
  1103. .. function:: void json_get_alloc_funcs(json_malloc_t *malloc_fn, json_free_t *free_fn)
  1104. Fetch the current malloc_fn and free_fn used. Either parameter
  1105. may be NULL.
  1106. .. versionadded:: 2.8
  1107. **Examples:**
  1108. Circumvent problems with different CRT heaps on Windows by using
  1109. application's :func:`malloc()` and :func:`free()`::
  1110. json_set_alloc_funcs(malloc, free);
  1111. Use the `Boehm's conservative garbage collector`_ for memory
  1112. operations::
  1113. json_set_alloc_funcs(GC_malloc, GC_free);
  1114. .. _Boehm's conservative garbage collector: http://www.hboehm.info/gc/
  1115. Allow storing sensitive data (e.g. passwords or encryption keys) in
  1116. JSON structures by zeroing all memory when freed::
  1117. static void *secure_malloc(size_t size)
  1118. {
  1119. /* Store the memory area size in the beginning of the block */
  1120. void *ptr = malloc(size + 8);
  1121. *((size_t *)ptr) = size;
  1122. return ptr + 8;
  1123. }
  1124. static void secure_free(void *ptr)
  1125. {
  1126. size_t size;
  1127. ptr -= 8;
  1128. size = *((size_t *)ptr);
  1129. guaranteed_memset(ptr, 0, size + 8);
  1130. free(ptr);
  1131. }
  1132. int main()
  1133. {
  1134. json_set_alloc_funcs(secure_malloc, secure_free);
  1135. /* ... */
  1136. }
  1137. For more information about the issues of storing sensitive data in
  1138. memory, see
  1139. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/protect-secrets.html.
  1140. The page also explains the :func:`guaranteed_memset()` function used
  1141. in the example and gives a sample implementation for it.