xref: /aosp_15_r20/external/sg3_utils/testing/sg_json_builder_test.c (revision 44704f698541f6367e81f991ef8bb54ccbf3fc18)
1 // SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause)
2 /*
3  * Simple streaming JSON writer
4  *
5  * This takes care of the annoying bits of JSON syntax like the commas
6  * after elements
7  *
8  * Authors:	Stephen Hemminger <[email protected]>
9  *
10  * Borrowed from Linux kernel [5.17.0]: tools/bpf/bpftool/json_writer.[hc]
11  */
12 
13 #include <stdio.h>
14 #include <stdbool.h>
15 #include <stdarg.h>
16 #include <assert.h>
17 #include <malloc.h>
18 #include <inttypes.h>
19 #include <stdint.h>
20 
21 #include "../lib/sg_json_builder.h"
22 
main(int argc,char ** argv)23 int main(int argc, char **argv)
24 {
25 	json_writer_t *wr = jsonw_new(stdout);
26 
27 	jsonw_start_object(wr);
28 	jsonw_pretty(wr, true);
29 	jsonw_name(wr, "Vyatta");
30 	jsonw_start_object(wr);
31 	jsonw_string_field(wr, "url", "http://vyatta.com");
32 	jsonw_uint_field(wr, "downloads", 2000000ul);
33 	jsonw_float_field(wr, "stock", 8.16);
34 
35 	jsonw_name(wr, "ARGV");
36 	jsonw_start_array(wr);
37 	while (--argc)
38 		jsonw_string(wr, *++argv);
39 	jsonw_end_array(wr);
40 
41 	jsonw_name(wr, "empty");
42 	jsonw_start_array(wr);
43 	jsonw_end_array(wr);
44 
45 	jsonw_name(wr, "NIL");
46 	jsonw_start_object(wr);
47 	jsonw_end_object(wr);
48 
49 	jsonw_null_field(wr, "my_null");
50 
51 	jsonw_name(wr, "special chars");
52 	jsonw_start_array(wr);
53 	jsonw_string_field(wr, "slash", "/");
54 	jsonw_string_field(wr, "newline", "\n");
55 	jsonw_string_field(wr, "tab", "\t");
56 	jsonw_string_field(wr, "ff", "\f");
57 	jsonw_string_field(wr, "quote", "\"");
58 	jsonw_string_field(wr, "tick", "\'");
59 	jsonw_string_field(wr, "backslash", "\\");
60 	jsonw_end_array(wr);
61 
62 jsonw_name(wr, "ARGV");
63 jsonw_start_array(wr);
64 jsonw_string(wr, "boo: appended or new entry?");
65 jsonw_end_array(wr);
66 
67 	jsonw_end_object(wr);
68 
69 	jsonw_end_object(wr);
70 	jsonw_destroy(&wr);
71 	return 0;
72 }
73 
74