json_object_get_string : Get string value of a json object

Posted by Joys of Programming on May 25, 2010 in C/C++, JSON, json-c |

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


char* json_object_get_string(struct json_object *);

It takes json_object as a parameter and returns back a string.

The following program demonstrates this. the function json_parse accepts a json_object with one or more key:string 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_string: printf("type: json_type_string, ");
 printf("value: %s\n", json_object_get_string(val));
 break;
 }
 }
}
int main() {
 char * string = "{ \"sitename\" : \"Joys of Programming\",\
 \"purpose\" : \"programming tips\",\
 \"platform\" : \"wordpress\"\
 }";
 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: { "sitename" : "Joys of Programming",                     "purpose" : "programming tips",                     "platform" : "wordpress"                     }
type: json_type_string, value: Joys of Programming
type: json_type_string, value: programming tips
type: json_type_string, value: wordpress

As you can see our input to the program was


{
 "sitename" : "Joys of Programming",
 "purpose" : "programming tips",
 "platform" : "wordpress"
}

with json_object_get_string, we are able to get the string values.

Related posts:

  1. json_object_object_get: Get a json object
  2. json_object_new_string- Create a new string json object
  3. json_object_is_type: Check the type of json object
  4. json_object_object_foreach : Browse through every json object
  5. json_object_get_array: Access an array 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.