json_object_object_get能否从json字符串中取出子json字符串
时间: 2023-12-06 12:05:15 浏览: 151
`json_object_object_get` 函数只能获取 JSON 对象中指定键名对应的值,并不能从 JSON 字符串中取出子 JSON 字符串。不过,可以通过将 JSON 字符串解析为 JSON 对象,再使用 `json_object_object_get` 函数获取子 JSON 对象的方式来实现。
例如,假设有一个 JSON 字符串如下:
```
{
"name": "Alice",
"age": 18,
"address": {
"province": "Beijing",
"city": "Beijing",
"district": "Haidian"
}
}
```
如果需要获取其中 `address` 的值,可以使用 `json_tokener_parse` 函数将 JSON 字符串解析为 JSON 对象,然后使用 `json_object_object_get` 函数获取 `address` 对应的子 JSON 对象。接着,可以使用 `json_object_to_json_string` 函数将子 JSON 对象转换为 JSON 字符串,如下所示:
```c
struct json_object *obj = json_tokener_parse(json_str);
struct json_object *address_obj = json_object_object_get(obj, "address");
if (address_obj != NULL) {
const char *address_str = json_object_to_json_string(address_obj);
printf("address: %s\n", address_str);
}
```
上述代码中,`json_tokener_parse` 函数用于将 JSON 字符串解析为 JSON 对象,然后使用 `json_object_object_get` 函数获取键名为 `address` 对应的子 JSON 对象。如果查找成功,则使用 `json_object_to_json_string` 函数将该子 JSON 对象转换为 JSON 字符串,并输出该字符串。输出结果如下:
```
address: {"province":"Beijing","city":"Beijing","district":"Haidian"}
```
需要注意的是,上述代码中获取到的 `address_str` 是一个 JSON 字符串,需要进一步解析才能获取其中的具体值。
阅读全文
相关推荐


















