json_object_get_array() is used to access an array within a json object. JSON contains key:value pairs, where value can be an array. The values within an array can also be an array, integer, boolean, double.
#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_array: printf("type: json_type_array, "); jobj = json_object_object_get(jobj, key); int arraylen = json_object_array_length(jobj); printf("Array Length: %dn",arraylen); int i; json_object * jvalue; for (i=0; i< arraylen; i++){ jvalue = json_object_array_get_idx(jobj, i); printf("value[%d]: %sn",i, json_object_get_string(jvalue)); } break; } } } int main() { char * string = "{ "tags": [ "c++", "php", "java"] }"; printf ("JSON string: %sn", 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: { "tags": [ "c++", "php", "java"] } type: json_type_array, Array Length: 3 value[0]: c++ value[1]: php value[2]: java
The input to the program was
{ "tags": [ "c++", "php", "java" ] }