-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonUtil.c
executable file
·95 lines (88 loc) · 2.67 KB
/
jsonUtil.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <json.h>
#include <stdio.h>
/*printing the value corresponding to boolean, double, integer and strings*/
void print_json_value(json_object *jobj)
{
enum json_type type;
printf("type: %d\n", type);
type = json_object_get_type(jobj); /*Getting the type of the json object*/
switch (type)
{
case json_type_boolean:
printf("json_type_boolean\n");
printf("value: %s\n", json_object_get_boolean(jobj) ? "true" : "false");
break;
case json_type_double:
printf("json_type_double\n");
printf(" value: %lf\n", json_object_get_double(jobj));
break;
case json_type_int:
printf("json_type_int\n");
printf(" value: %d\n", json_object_get_int(jobj));
break;
case json_type_string:
printf("json_type_string\n");
printf(" value: %s\n", json_object_get_string(jobj));
break;
}
}
void json_parse_array(json_object *jobj, char *key)
{
void json_parse(json_object * jobj); /*Forward Declaration*/
enum json_type type;
json_object *jarray = jobj; /*Simply get the array*/
if (key)
{
jarray = json_object_object_get(jobj, key); /*Getting the array if it is a key value pair*/
}
int arraylen = json_object_array_length(jarray); /*Getting the length of the array*/
printf("Array Length: %d\n", arraylen);
int i;
json_object *jvalue;
for (i = 0; i < arraylen; i++)
{
jvalue = json_object_array_get_idx(jarray, i); /*Getting the array element at position i*/
type = json_object_get_type(jvalue);
if (type == json_type_array)
{
json_parse_array(jvalue, NULL);
}
else if (type != json_type_object)
{
printf("value[%d]: \n", i);
print_json_value(jvalue);
}
else
{
json_parse(jvalue);
}
}
}
/*Parsing the json object*/
void json_parse(json_object *jobj)
{
enum json_type type;
json_object_object_foreach(jobj, key, val)
{ /*Passing through every array element*/
printf("type: %d\n", type);
type = json_object_get_type(val);
switch (type)
{
case json_type_boolean:
case json_type_double:
case json_type_int:
case json_type_string:
print_json_value(val);
break;
case json_type_object:
printf("json_type_object\n");
jobj = json_object_object_get(jobj, key);
json_parse(jobj);
break;
case json_type_array:
printf("type: json_type_array\n");
json_parse_array(jobj, key);
break;
}
}
}