json_object_get_int : Get integer value of a json object

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: %dn", json_object_get_int(val));
int main() {
 char * string = "{ "colors" : 7,
 "continents" : 7,
 "oceans" : 5
 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: { "colors" : 7,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "continents" : 7,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "oceans" : 5&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
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.

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