如何在json_tokener_parse()之后获取json值? [英] How to get json values after json_tokener_parse()?
问题描述
我有以下代码
#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);
}
我知道我们必须使用json_tokener_parse()
来解析json字符串,但是我不知道如何从json_object 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
如何在json_tokener_parse()
之后获取json值?
How to get json values after json_tokener_parse()
?
推荐答案
首先,您需要将json_object
获取到特定节点:
First you need to get the json_object
to a specific node:
json_object *obj_foo = json_object_object_get(new_obj, "foo");
...然后,您可以使用适当的getter来获取特定类型的节点的值:
...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.
这篇关于如何在json_tokener_parse()之后获取json值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!