e236248d8a24be976cdbbd0ec8ab69151895738c
[AGL/documentation.git] / docs / 3_Developer_Guides / 6_AFB_Helper_Guide / 3.7.8_C_JSON_Wrapper.md
1 ---
2 edit_link: ''
3 title: C JSON Wrapper
4 origin_url: >-
5   https://git.automotivelinux.org/src/libafb-helpers/plain/docs/wrap-json.md?h=master
6 ---
7
8 <!-- WARNING: This file is generated by fetch_docs.js using /home/boron/Documents/AGL/docs-webtemplate/site/_data/tocs/devguides/master/afb-helpers-function-references-afb-helpers-book.yml -->
9
10 WRAP-JSON facility
11 ==================
12
13 The facility wrap-json is based on the pack/unpack API on the
14 library jansson. The two chapters below are copied from the
15 documentation of jansson library copyrighted by Petri Lehtinen
16 (see at end).
17
18 Building Values
19 ---------------
20
21 This section describes functions that help to create, or *pack*, complex
22 JSON values, especially nested objects and arrays. Value building is
23 based on a *format string* that is used to tell the functions about the
24 expected arguments.
25
26 For example, the format string `"i"` specifies a single integer value,
27 while the format string `"[ssb]"` or the equivalent `"[s, s, b]"`
28 specifies an array value with two strings and a boolean as its items:
29
30     /* Create the JSON integer 42 */
31     wrap_json_pack(&result, "i", 42);
32
33     /* Create the JSON array ["foo", "bar", true] */
34     wrap_json_pack(&result, "[ssb]", "foo", "bar", 1);
35
36 Here's the full list of format specifiers. The type in parentheses
37 denotes the resulting JSON type, and the type in brackets (if any)
38 denotes the C type that is expected as the corresponding argument or
39 arguments.
40
41 `s` (string) \[const char \*\]
42
43 : Convert a null terminated UTF-8 string to a JSON string.
44
45 `s?` (string) \[const char \*\]
46
47 : Like `s`, but if the argument is *NULL*, output a JSON null value.
48
49 `s*` (string) \[const char \*\]
50
51 : Like `s`, but if the argument is *NULL*, do not output any value.
52     This format can only be used inside an object or an array. If used
53     inside an object, the corresponding key is additionally suppressed
54     when the value is omitted. See below for an example.
55
56 `s#` (string) \[const char \*, int\]
57
58 : Convert a UTF-8 buffer of a given length to a JSON string.
59
60 `s%` (string) \[const char \*, size\_t\]
61
62 : Like `s#` but the length argument is of type size\_t.
63
64 `+` \[const char \*\]
65
66 : Like `s`, but concatenate to the previous string. Only valid after
67     `s`, `s#`, `+` or `+#`.
68
69 `+#` \[const char \*, int\]
70
71 : Like `s#`, but concatenate to the previous string. Only valid after
72     `s`, `s#`, `+` or `+#`.
73
74 `+%` (string) \[const char \*, size\_t\]
75
76 : Like `+#` but the length argument is of type size\_t.
77
78 `y` (byte array) \[const uint8_t \*, size\_t\]
79
80 : Convert the byte array whose length is given to
81     its base64url string representation.
82
83 `Y` (byte array) \[const uint8_t \*, size\_t\]
84
85 : Like 'y' but output is base64.
86
87 `y?`, `Y?` (byte array or null) \[const uint8_t \*, size\_t\]
88
89 : Like 'y' or 'Y' but allows to output a JSON null value
90     either when the buffer is *NULL* or when the size is *0*.
91
92 `y*`, `y*` (optional byte array) \[const uint8_t \*, size\_t\]
93
94 : Like 'y' or 'Y' but do not put JSON value
95   either when the buffer is *NULL* or when the size is *0*.
96   This format can only be used inside an object or an array. If used
97   inside an object, the corresponding key is additionally suppressed
98   when the value is omitted. See below for an example.
99
100 `n` (null)
101
102 : Output a JSON null value. No argument is consumed.
103
104 `b` (boolean) \[int\]
105
106 : Convert a C int to JSON boolean value. Zero is converted to `false`
107     and non-zero to `true`.
108
109 `i` (integer) \[int\]
110
111 : Convert a C int to JSON integer.
112
113 `I` (integer) \[json\_int\_t\]
114
115 : Convert a C json\_int\_t to JSON integer.
116
117 `f` (real) \[double\]
118
119 : Convert a C double to JSON real.
120
121 `o` (any value) \[json\_t \*\]
122
123 : Output any given JSON value as-is. If the value is added to an array
124   or object, the reference to the value passed to `o` is stolen by the
125   container.
126
127 `O` (any value) \[json\_t \*\]
128
129 : Like `o`, but the argument's reference count is incremented. This is
130   useful if you pack into an array or object and want to keep the
131   reference for the JSON value consumed by `O` to yourself.
132
133 `o?`, `O?` (any value) \[json\_t \*\]
134
135 : Like `o` and `O`, respectively, but if the argument is *NULL*,
136   output a JSON null value.
137
138 `o*`, `O*` (any value) \[json\_t \*\]
139
140 : Like `o` and `O`, respectively, but if the argument is *NULL*, do
141   not output any value. This format can only be used inside an object
142   or an array. If used inside an object, the corresponding key is
143   additionally suppressed. See below for an example.
144
145 `[fmt]` (array)
146
147 : Build an array with contents from the inner format string. `fmt` may
148   contain objects and arrays, i.e. recursive value building is
149   supported.
150
151 `{fmt}` (object)
152
153 : Build an object with contents from the inner format string `fmt`.
154   The first, third, etc. format specifier represent a key, and must be
155   a string (see `s`, `s#`, `+` and `+#` above), as object keys are
156   always strings. The second, fourth, etc. format specifier represent
157   a value. Any value may be an object or array, i.e. recursive value
158   building is supported.
159
160 Whitespace, `:` and `,` are ignored.
161
162 More examples:
163
164     /* Build an empty JSON object */
165     wrap_json_pack(&result, "{}");
166
167     /* Build the JSON object {"foo": 42, "bar": 7} */
168     wrap_json_pack(&result, "{sisi}", "foo", 42, "bar", 7);
169
170     /* Like above, ':', ',' and whitespace are ignored */
171     wrap_json_pack(&result, "{s:i, s:i}", "foo", 42, "bar", 7);
172
173     /* Build the JSON array [[1, 2], {"cool": true}] */
174     wrap_json_pack(&result, "[[i,i],{s:b}]", 1, 2, "cool", 1);
175
176     /* Build a string from a non-null terminated buffer */
177     char buffer[4] = {'t', 'e', 's', 't'};
178     wrap_json_pack(&result, "s#", buffer, 4);
179
180     /* Concatenate strings together to build the JSON string "foobarbaz" */
181     wrap_json_pack(&result, "s++", "foo", "bar", "baz");
182
183     /* Create an empty object or array when optional members are missing */
184     wrap_json_pack(&result, "{s:s*,s:o*,s:O*}", "foo", NULL, "bar", NULL, "baz", NULL);
185     wrap_json_pack(&result, "[s*,o*,O*]", NULL, NULL, NULL);
186
187 Parsing and Validating Values
188 -----------------------------
189
190 This section describes functions that help to validate complex values
191 and extract, or *unpack*, data from them. Like building values
192 &lt;apiref-pack&gt;, this is also based on format strings.
193
194 While a JSON value is unpacked, the type specified in the format string
195 is checked to match that of the JSON value. This is the validation part
196 of the process. In addition to this, the unpacking functions can also
197 check that all items of arrays and objects are unpacked. This check be
198 enabled with the format specifier `!` or by using the flag
199 `JSON_STRICT`. See below for details.
200
201 Here's the full list of format specifiers. The type in parentheses
202 denotes the JSON type, and the type in brackets (if any) denotes the C
203 type whose address should be passed.
204
205 `s` (string) \[const char \*\]
206
207 : Convert a JSON string to a pointer to a null terminated UTF-8
208   string. The resulting string is extracted by using
209   json\_string\_value() internally, so it exists as long as there are
210   still references to the corresponding JSON string.
211
212 `s%` (string) \[const char \*, size\_t \*\]
213
214 : Convert a JSON string to a pointer to a null terminated UTF-8 string
215   and its length.
216
217 `y` (byte array) \[uint8_t \*\*, size\_t \*\]
218
219 : Convert an input string base64url encoded to its
220   byte array representation. The result and its length
221   are stored. The returned buffer must be freed by the caller.
222
223 `Y` (byte array) \[uint8_t \*\*, size\_t \*\]
224
225 : Like 'y' but input is base64.
226
227 `n` (null)
228
229 : Expect a JSON null value. Nothing is extracted.
230
231 `b` (boolean) \[int\]
232
233 : Convert a JSON boolean value to a C int, so that `true` is converted
234   to 1 and `false` to 0.
235
236 `i` (integer) \[int\]
237
238 : Convert a JSON integer to C int.
239
240 `I` (integer) \[json\_int\_t\]
241
242 : Convert a JSON integer to C json\_int\_t.
243
244 `f` (real) \[double\]
245
246 : Convert a JSON real to C double.
247
248 `F` (integer or real) \[double\]
249
250 : Convert a JSON number (integer or real) to C double.
251
252 `o` (any value) \[json\_t \*\]
253
254 : Store a JSON value with no conversion to a json\_t pointer.
255
256 `O` (any value) \[json\_t \*\]
257
258 : Like `O`, but the JSON value's reference count is incremented.
259
260 `[fmt]` (array)
261
262 : Convert each item in the JSON array according to the inner format
263   string. `fmt` may contain objects and arrays, i.e. recursive value
264   extraction is supported.
265
266 `{fmt}` (object)
267
268 : Convert each item in the JSON object according to the inner format
269   string `fmt`. The first, third, etc. format specifier represent a
270   key, and must be `s`. The corresponding argument to unpack functions
271   is read as the object key. The second fourth, etc. format specifier
272   represent a value and is written to the address given as the
273   corresponding argument. **Note** that every other argument is read
274   from and every other is written to.
275
276     `fmt` may contain objects and arrays as values, i.e. recursive value
277     extraction is supported.
278
279 `!`
280
281 : This special format specifier is used to enable the check that all
282   object and array items are accessed, on a per-value basis. It must
283   appear inside an array or object as the last format specifier before
284   the closing bracket or brace.
285
286 `*`
287
288 : This special format specifier is the opposite of `!`. This is the default.
289   It must appear inside an array or object as the last format specifier
290   before the closing bracket or brace.
291
292 Whitespace, `:` and `,` are ignored.
293
294 Examples:
295
296     /* root is the JSON integer 42 */
297     int myint;
298     wrap_json_unpack(root, "i", &myint);
299     assert(myint == 42);
300
301     /* root is the JSON object {"foo": "bar", "quux": true} */
302     const char *str;
303     int boolean;
304     wrap_json_unpack(root, "{s:s, s:b}", "foo", &str, "quux", &boolean);
305     assert(strcmp(str, "bar") == 0 && boolean == 1);
306
307     /* root is the JSON array [[1, 2], {"baz": null} */
308     wrap_json_check(root, "[[i,i], {s:n}]", "baz");
309     /* returns 0 for validation success, nothing is extracted */
310
311     /* root is the JSON array [1, 2, 3, 4, 5] */
312     int myint1, myint2;
313     wrap_json_unpack(root, "[ii!]", &myint1, &myint2);
314     /* returns -1 for failed validation */
315
316     /* root is an empty JSON object */
317     int myint = 0, myint2 = 0, myint3 = 0;
318     wrap_json_unpack(root, "{s?i, s?[ii]}",
319                 "foo", &myint1,
320                 "bar", &myint2, &myint3);
321     /* myint1, myint2 or myint3 is no touched as "foo" and "bar" don't exist */
322
323 Copyright
324 ---------
325
326 Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
327
328 Permission is hereby granted, free of charge, to any person obtaining a copy
329 of this software and associated documentation files (the "Software"), to deal
330 in the Software without restriction, including without limitation the rights
331 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
332 copies of the Software, and to permit persons to whom the Software is
333 furnished to do so, subject to the following conditions:
334
335 The above copyright notice and this permission notice shall be included in
336 all copies or substantial portions of the Software.
337
338 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
339 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
340 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
341 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
342 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
343 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
344 THE SOFTWARE.