add a json to blobmsg parsing library
[project/libubox.git] / blobmsg_json.c
1 #include "blobmsg.h"
2 #include "blobmsg_json.h"
3
4 static bool blobmsg_add_object(struct blob_buf *b, json_object *obj)
5 {
6 json_object_object_foreach(obj, key, val) {
7 if (!blobmsg_add_json_element(b, key, val))
8 return false;
9 }
10 return true;
11 }
12
13 static bool blobmsg_add_array(struct blob_buf *b, struct array_list *a)
14 {
15 int i, len;
16
17 for (i = 0, len = array_list_length(a); i < len; i++) {
18 if (!blobmsg_add_json_element(b, NULL, array_list_get_idx(a, i)))
19 return false;
20 }
21
22 return true;
23 }
24
25 bool blobmsg_add_json_element(struct blob_buf *b, const char *name, json_object *obj)
26 {
27 bool ret = true;
28 void *c;
29
30 if (!obj)
31 return false;
32
33 switch (json_object_get_type(obj)) {
34 case json_type_object:
35 c = blobmsg_open_table(b, name);
36 ret = blobmsg_add_object(b, obj);
37 blobmsg_close_table(b, c);
38 break;
39 case json_type_array:
40 c = blobmsg_open_array(b, name);
41 ret = blobmsg_add_array(b, json_object_get_array(obj));
42 blobmsg_close_array(b, c);
43 break;
44 case json_type_string:
45 blobmsg_add_string(b, name, json_object_get_string(obj));
46 break;
47 case json_type_boolean:
48 blobmsg_add_u8(b, name, json_object_get_boolean(obj));
49 break;
50 case json_type_int:
51 blobmsg_add_u32(b, name, json_object_get_int(obj));
52 break;
53 default:
54 return false;
55 }
56 return ret;
57 }
58
59 bool blobmsg_add_json_from_string(struct blob_buf *b, const char *str)
60 {
61 json_object *obj;
62 bool ret = false;
63
64 obj = json_tokener_parse(str);
65 if (is_error(obj))
66 return false;
67
68 if (json_object_get_type(obj) != json_type_object)
69 goto out;
70
71 ret = blobmsg_add_object(b, obj);
72
73 out:
74 json_object_put(obj);
75 return ret;
76 }
77