0

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 Answers1

1

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_nulln");
    break;
  case json_type_boolean:
    printf("json_type_booleann");
    break;
  case json_type_double:
    printf("json_type_doublen");
    break;
  case json_type_int:
    printf("json_type_intn");
    break;
  case json_type_object:
    printf("json_type_objectn");
    break;
  case json_type_array:
    printf("json_type_arrayn");
    break;
  case json_type_string:
    printf("json_type_stringn");
    break;
  }
}
}
Njuguna Mureithi
  • 3,506
  • 1
  • 21
  • 41