Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get json values after json_tokener_parse()?

Tags:

json

c

libjson

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() ?

like image 886
MOHAMED Avatar asked Oct 15 '25 02:10

MOHAMED


1 Answers

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.

like image 178
netcoder Avatar answered Oct 17 '25 18:10

netcoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!