How to get json values after json_tokener_parse()?

c, json, libjson

Solution

First you need to get the `json_object` to a specific node:

json_object *obj_foo = json_object_object_get(new_obj, "foo");

...then you can use the appropriate getter to obtain the value of the node in a specific type:

char *foo_val = json_object_get_string(obj_foo2);

So, in short, you could do:

printf("The value of foo is %s", 
    json_object_get_string(json_object_object_get(new_obj, "foo"))
);

Obviously, it's better to do it in multiple steps so that you can check for errors (in this case: null pointers) and prevent undefined behavior and such.

You can find the JSON C API documentation here.

Problem

I have the following code ``` #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <json/json.h> int main(int argc, char **argv) { json_object *new_obj; char buf[] = "{ \"foo\": \"bar\", \"foo2\": \"bar2\", \"foo3\": \"bar3\" }" new_obj = json_tokener_parse(buf); printf("The value of foo is %s" /*What I have to put here?*/); printf("The value of foo2 is %s" /*What I have to put here?*/); printf("The value of foo3 is %s" /*What I have to put here?*/); json_object_put(new_obj); } ``` I knwo that we have to use `json_tokener_parse()` to parse json strings but then I do not know how to extract values from the json_object `new_obj` as indicated in the comments in the code above How to get json values after `json_tokener_parse()` ?

Original source