Search code examples
cjsonjson-c

Key names in json-c


I'm using json-c to parse the following JSON string:

{
  "root": {
    "a": "1",
    "b": "2",
    "c": "3"
  }
}

And, I have the following C code. The above JSON is stored in the variable, b.

json_object *new_obj, *obj1, *obj2;
int exists;

new_obj = json_tokener_parse(b); 
exists=json_object_object_get_ex(new_obj,"a",&obj1); 
if(exists==false) { 
  printf("key \"a\" not found in JSON"); 
  return; 
} 
exists=json_object_object_get_ex(new_obj,"b",&obj2); 
if(exists==false) { 
  printf("key \"b\" not found in JSON"); 
  return; 
}

What is the correct key name to use for getting the value from key "a" using json_object_get_ex?

What I have doesn't work (exists is false for both queries) for the JSON I have above, but it does work for the following JSON. I'm certain this has to do with a misunderstanding about which key to use for the "path" to key "a".

{      
   "a": "1",
   "b": "2",
   "c": "3"
}

Solution

  • OK, I figured it out, and like I said I was misunderstanding how json-c was parsing the original JSON text and representing it as parent and child nodes.

    This following code is working. The problem was that I was trying to get the child nodes from the original json_object, which was not correct. I first had to get the root object and then get the child objects from the root.

    json_object *new_obj, *root_obj, *obj1, *obj2;
    int exists;
    
    new_obj = json_tokener_parse(b); 
    exists=json_object_object_get_ex(new_obj,"root",&root_obj);
    if(exists==false) { 
      printf("\"root\" not found in JSON"); 
      return; 
    } 
    exists=json_object_object_get_ex(root_obj,"a",&obj1); 
    if(exists==false) { 
      printf("key \"a\" not found in JSON"); 
      return; 
    } 
    exists=json_object_object_get_ex(root_obj,"b",&obj2); 
    if(exists==false) { 
      printf("key \"b\" not found in JSON"); 
      return; 
    }