Please use the below sample to reproduce this issue.
/**************************************************/
#include <stdio.h>
#include <json/json.h>
json_object* createJsonObject (char *string);
void extractJsonValue (json_object * obj, char *key);
void parseJsonArray (json_object * jobj, char *key);
void parseJsonObject (json_object * jobj);
json_object* createJsonObject (char *string)
{
struct json_tokener* tok = NULL;
json_object *jobj = NULL;
enum json_tokener_error error = json_tokener_error_parse_null;
if (NULL == string)
return NULL;
tok = json_tokener_new();
if (tok)
{
jobj = json_tokener_parse_ex(tok, string, -1);
if(json_tokener_success == (enum json_tokener_error)tok->err && jobj)
{
printf ("Object created successfully.\n");
}
else
{
jobj = NULL;
printf ("Object creation failed.\n");
}
json_tokener_free(tok);
}
return jobj;
}
void extractJsonValue (json_object * obj, char *key)
{
enum json_type type = json_object_get_type (obj);
switch (type)
{
case json_type_boolean:
printf("key: %s val: %s\n", key, (json_object_get_boolean(obj)?"true":"false"));
break;
case json_type_double:
printf("key: %s val: %f\n", key, json_object_get_double(obj));
break;
case json_type_int:
printf("key: %s val: %d\n", key, json_object_get_int(obj));
break;
case json_type_string:
printf("key: %s val: %s\n", key, json_object_get_string(obj));
break;
default:
printf("key: %s is unknown type\n", key);
break;
}
}
void parseJsonArray (json_object * jobj, char *key)
{
enum json_type type;
/*Simply get the array */
json_object *jarray = jobj;
if (key)
{
/*Getting the array if it is a key value pair */
jarray = json_object_object_get (jobj, key);
}
/*Getting the length of the array */
int arraylen = json_object_array_length (jarray);
json_object *jvalue;
int i;
for (i = 0; i < arraylen; i++)
{
/*Getting the array element at position i */
jvalue = json_object_array_get_idx (jarray, i);
type = json_object_get_type (jvalue);
switch (type)
{
case json_type_boolean:
case json_type_double:
case json_type_int:
case json_type_string:
extractJsonValue (jvalue, key);
break;
case json_type_object:
parseJsonObject (jvalue);
break;
case json_type_array:
parseJsonArray (jvalue, NULL);
break;
}
}
}
void parseJsonObject (json_object * jobj)
{
enum json_type type;
json_object_object_foreach (jobj, key, val)
/*Passing through every array element */
{
type = json_object_get_type (val);
switch (type)
{
case json_type_boolean:
case json_type_double:
case json_type_int:
case json_type_string:
extractJsonValue (val, key);
break;
case json_type_object:
jobj = json_object_object_get (jobj, key);
parseJsonObject (jobj);
break;
case json_type_array:
parseJsonArray (jobj, key);
break;
}
}
}
int main(int argc, char **argv)
{
if (argc <= 1)
{
printf("not enough args\n");
return 1;
}
json_object *obj;
enum json_type type;
obj = createJsonObject(argv[1]);
if (!obj)
return 1;
parseJsonObject (obj);
json_object_put(obj);
return 0;
}
/*************************************************/