How to loop through keys and values in C using the json-c library?

2k views Asked by At

I'm using json-c to parse json. Is it possible to loop through the keys and values. json_object_object_get_ex() : this function requires prior knowledge what the keys are. What if we don't know the keys and we have to loop through them.

1

There are 1 answers

0
Njuguna Mureithi On

You can start at the json_object_object_foreach macro

#define json_object_object_foreach(obj, key, val)
char * key;
struct json_object * val;
for (struct lh_entry * entry = json_object_get_object(obj) -> head;
  ({
    if (entry) {
      key = (char * ) entry -> k;
      val = (struct json_object * ) entry -> v;
    };entry;
  }); entry = entry -> next)

For usage, this article has a good example.

#include <json/json.h>

#include <stdio.h>

int main() {
  char * string = "{"
  sitename " : "
  joys of programming ",
  "tags": ["c", "c++", "java", "PHP"],
  "author-details": {
    "name": "Joys of Programming",
    "Number of Posts": 10
  }
}
";
json_object * jobj = json_tokener_parse(string);
enum json_type type;
json_object_object_foreach(jobj, key, val) {
  printf("type: ", type);
  type = json_object_get_type(val);
  switch (type) {
  case json_type_null:
    printf("json_type_null\n");
    break;
  case json_type_boolean:
    printf("json_type_boolean\n");
    break;
  case json_type_double:
    printf("json_type_double\n");
    break;
  case json_type_int:
    printf("json_type_int\n");
    break;
  case json_type_object:
    printf("json_type_object\n");
    break;
  case json_type_array:
    printf("json_type_array\n");
    break;
  case json_type_string:
    printf("json_type_string\n");
    break;
  }
}
}