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


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_nulln");
 case json_type_boolean: printf("json_type_booleann");
 case json_type_double: printf("json_type_doublen");
 case json_type_int: printf("json_type_intn");
 case json_type_object: printf("json_type_objectn");
 case json_type_array: printf("json_type_arrayn");
 case json_type_string: printf("json_type_stringn");

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s