json_object_get_array: Access an array JSON object

Posted by Joys of Programming on June 1, 2010 in C/C++, JSON, Linux, json-c |

json_object_get_array() is used to access an array within a  json object. JSON contains key:value pairs, where value can be an array. The values within an array can also be an array, integer, boolean, double.

#include <json/json.h>
#include <stdio.h>

void json_parse(json_object * jobj) {
  enum json_type type;
  json_object_object_foreach(jobj, key, val) {
    type = json_object_get_type(val);
    switch (type) {
      case json_type_array: printf("type: json_type_array, ");
                          jobj = json_object_object_get(jobj, key);
                          int arraylen = json_object_array_length(jobj);
                          printf("Array Length: %d\n",arraylen);
                          int i;
                          json_object * jvalue;
                          for (i=0; i< arraylen; i++){
                            jvalue = json_object_array_get_idx(jobj, i);
                            printf("value[%d]: %s\n",i, json_object_get_string(jvalue));
                          }
                          break;
    }
  }
}
int main() {
  char * string = "{ \"tags\": [ \"c++\", \"php\", \"java\"] \
                     }";
  printf ("JSON string: %s\n", string);
  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: { "tags": [ "c++", "php", "java"]                      }
type: json_type_array, Array Length: 3
value[0]: c++
value[1]: php
value[2]: java

The input to the program was

{
    "tags": [
        "c++",
        "php",
        "java"
    ]
}

Related posts:

  1. json_object_array_add- Add json object to Array
  2. json_object_new_array- Create a new array json object
  3. json_object_array_put_idx- Add json object to Array at specified index
  4. A simple and complete json parser
  5. json_object_is_type: Check the type of json object

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv Enabled

Copyright © 2009-2010 Joys of Programming All rights reserved.
Desk Mess Mirrored v1.7.2 theme from BuyNowShop.com.