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.
Asked
Active
Viewed 1,483 times
0
-
1Take a look at https://json-c.github.io/json-c/json-c-0.10/doc/html/json__object_8h.html#acf5f514a9e0061c10fc08055762639ee – Njuguna Mureithi Sep 16 '21 at 16:50
-
@NjugunaMureithi can you please explain how does it work. What is it returning, or how can I efficiently use it. Since it is a macro I'm struggling to understand the usage – Faris Kamal Kakkengal Sep 17 '21 at 04:17
-
1Hey man, I am not sure what you are asking me to do specifically. Can you post your code? Have you done some searches on it? Eg. This was on page 1: https://linuxprograms.wordpress.com/2010/05/24/json_object_object_foreach/ – Njuguna Mureithi Sep 17 '21 at 05:51
-
@NjugunaMureithi Thanks man for this article. Now I understood how to use it. Appreciate it!! – Faris Kamal Kakkengal Sep 17 '21 at 06:44
-
Provided an answer – Njuguna Mureithi Sep 17 '21 at 06:52
1 Answers
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