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