json_object_object_get: Get a json object
json_object_object_get() is used to get the json object. JSON contains key:value pairs. The value can be an array, integer, boolean, double. It can also be a json object. That means to access the values within the json object, we must recursively go through json objects. The following program shows this
#include <json/json.h>
#include <stdio.h>
void json_parse(json_object * jobj) {
enum json_type type;
json_object_object_foreach(jobj, key, val) {
printf("type: ",type);
type = json_object_get_type(val);
switch (type) {
case json_type_null: printf("json_type_null\n");
break;
case json_type_boolean: printf("json_type_boolean\n");
printf(" value: %d\n", json_object_get_boolean(val));
break;
case json_type_double: printf("json_type_double\n");
printf(" value: %lf\n", json_object_get_double(val));
break;
case json_type_int: printf("json_type_int\n");
printf(" value: %d\n", json_object_get_int(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_string: printf("json_type_string\n");
printf(" value: %s\n", json_object_get_string(val));
break;
}
}
}
int main() {
char * string = "{\"sitename\" : \"joys of programming\",\
\"author-details\": { \"admin\": false, \"name\" : \"Joys of Programming\", \"Number of Posts\" : 10 } \
}";
json_object * jobj = json_tokener_parse(string);
json_parse(jobj);
}
Let’s compile the program. If you fail any compilation issues, refer the post.
On executing the program, we get the following output
$ ./a.out
JSON string: {"sitename" : "joys of programming", "author-details": { "admin": false, "name" : "Joys of Programming", "Number of Posts" : 10 } }
type: json_type_string
value: joys of programming
type: json_type_object
type: json_type_boolean
value: 0
type: json_type_string
value: Joys of Programming
type: json_type_int
value: 10
The input to the program was
{
"sitename" : "joys of programming",
"author-details": {
"admin": false,
"name" : "Joys of Programming",
"Number of Posts" : 10
}
}
As you can see that “author-details” is again a json object. See how the json_object_object_get() is recursively used to parse the json objects