3

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"
}
cigarman
  • 635
  • 6
  • 15
  • 1
    Seems you should get the "root" object first, then from that object, get the "a" and "b" objects. – caveman Apr 18 '15 at 00:02
  • Your question now contains the answer. Maybe you should extract the answer into a self-answer and then, in due course (a couple of days later), you'll be able to accept it (no points for doing so), and give closure to the question. – Jonathan Leffler Apr 18 '15 at 18:39
  • Jonathan, thanks, that's exactly what I'll do. – cigarman Apr 18 '15 at 20:59

1 Answers1

2

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; 
}
cigarman
  • 635
  • 6
  • 15