json_object_get_array: Access an array JSON object

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: %dn",arraylen);
                          int i;
                          json_object * jvalue;
                          for (i=0; i< arraylen; i++){
                            jvalue = json_object_array_get_idx(jobj, i);
                            printf("value[%d]: %sn",i, json_object_get_string(jvalue));
int main() {
  char * string = "{ "tags": [ "c++", "php", "java"] 
  printf ("JSON string: %sn", string);
  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: { "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": [

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s