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_nulln");
      case json_type_boolean: printf("json_type_booleann");
                           printf("          value: %dn", json_object_get_boolean(val));
      case json_type_double: printf("json_type_doublen");
                          printf("          value: %lfn", json_object_get_double(val));
      case json_type_int: printf("json_type_intn");
                          printf("          value: %dn", json_object_get_int(val));
      case json_type_object: printf("json_type_objectn");
                           jobj = json_object_object_get(jobj, key);
      case json_type_string: printf("json_type_stringn");
                           printf("          value: %sn", json_object_get_string(val));
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);

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


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