json_object_get_string : Get string value of a json object
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.