json_object_get_int : Get integer value of a json object

Posted by Joys of Programming on in C/C++, JSON, Web

json_object_get_int() function is used to get the integer value of a json object. The syntax


int json_object_get_int(struct json_object *);

It takes json_object as a parameter and returns back an integer.

The following program demonstrates this. the function json_parse accepts a json_object with one or more key:integer pairs.


#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_int: printf("type: json_type_int, ");
 printf("value: %d\n", json_object_get_int(val));
 break;
 }
 }
}
int main() {
 char * string = "{ \"colors\" : 7,\
 \"continents\" : 7,\
 \"oceans\" : 5\
 }";
 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: { "colors" : 7,                     "continents" : 7,                     "oceans" : 5                     }
type: json_type_int, value: 7
type: json_type_int, value: 7
type: json_type_int, value: 5

As you can see our input to the program was


{
 "colors" : 7,
 "continents" : 7,
 "oceans" : 5
}

with json_object_get_int, we are able to get the integer values.

Tags: , , , ,

Comments:

2 Comments

  • Abhishek says:

    Can you highlight an example for the usage of “extern struct array_list* json_object_get_array(struct json_object *obj)”. I need an example where I can get an array from json object

  • Joys of Programming says:

    Check Json Parser

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.