json_object_object_foreach : Browse through every json object
You can browse through every json object using the macro json_object_object_foreach
The syntax
json_object_object_foreach(obj,key,val)
where obj is the json object you want to parse, key and value correspond to key: value pairs. As mentioned before, json_object_object_foreach is a macro defined something like this
#define json_object_object_foreach(obj,key,val) \
char *key; struct json_object *val; \
for(struct lh_entry *entry = json_object_get_object(obj)->head; ({ if(entry) { key = (char*)entry->k; val = (struct json_object*)entry->v; } ; entry; }); entry = entry->next )
So key, val are not some variables, but you can choose any random strings to correspond to key and value
The following program depicts this
#include <json/json.h>
#include <stdio.h>
int main() {
char * string = "{\"sitename\" : \"joys of programming\",\
\"tags\" : [ \"c\" , \"c++\", \"java\", \"PHP\" ],\
\"author-details\": { \"name\" : \"Joys of Programming\", \"Number of Posts\" : 10 } \
}";
json_object * jobj = json_tokener_parse(string);
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");
break;
case json_type_double: printf("json_type_double\n");
break;
case json_type_int: printf("json_type_int\n");
break;
case json_type_object: printf("json_type_object\n");
break;
case json_type_array: printf("json_type_array\n");
break;
case json_type_string: printf("json_type_string\n");
break;
}
}
}
Now let’s compile the program
$ gcc json_object_object_foreach.c -l json json_object_object_foreach.c: In function ‘main’: json_object_object_foreach.c:9: error: ‘for’ loop initial declarations are only allowed in C99 mode json_object_object_foreach.c:9: note: use option -std=c99 or -std=gnu99 to compile your code
Oh, there are some errors, as you can see. This can be resolved by the option -std=c99
gcc json_object_object_foreach.c -ljson -std=c99
Let’s execute the program
$ ./a.out type: json_type_string type: json_type_array type: json_type_object
This program is not generic in nature. It has not shown the details of “author-details“. But you can write a recursive function to go through all the elements using json_object_object_foreach.
Comments: