json_object_array_put_idx- Add json object to Array at specified index

Posted by Joys of Programming on in json-c

json_object_array_add is used to add a json object to an array. Using json_object_array_put_idx, we can put a json object at a specified index

The syntax of the function is

int json_object_array_put_idx (struct json_object *this, int idx, struct json_object *val)

Specify the object where the json object has to be added, index and the value (json object) as the arguments

When you specify objects at some particular index, you may miss (intentionally) objects at some indices. The values at those indices will be null

The following program shows the usage of the function


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

int main() {
  /*Creating a json object*/
  json_object * jobj = json_object_new_object();

  /*Creating a json array*/
  json_object *jarray = json_object_new_array();

  /*Creating json strings*/
  json_object *jstring[3];
  jstring[0] = json_object_new_string("c");
  jstring[1] = json_object_new_string("c++");
  jstring[2] = json_object_new_string("php");

  /*Adding the above created json strings to the array*/
  int i;
  for (i=0;i<3; i++) {
    json_object_array_put_idx(jarray,i+2, jstring[i]);
  }

  /*Form the json object*/
  json_object_object_add(jobj,"Categories", jarray);

  /*Now printing the json object*/
  printf ("The json object created: %s\n",json_object_to_json_string(jobj));

}


The output of the program is something like this

The json object created: { "Categories": [ null, null, "c", "c++", "php" ] }


Tags: , , , , ,

Comments:

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>

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