如何解析下面的json{ "labels": [ { "0": "person", "1": "helmet", "2": "clothes", "3": "smoke", "4": "phone", "5": "fire", "6": "soot" } ], "tracks": [ { "person": { "attribute": [ "clothes", "helmet" ], "other": [ "phone", "smoke" ] } }, { "scene": { "safe": [], "alarm": [ "fire", "soot" ] } } ] }
时间: 2023-07-21 22:17:07 浏览: 140
你可以使用nlohmann_json库来解析这个JSON数据。对于这个JSON数据,可以使用以下代码来解析它:
```c++
#include <nlohmann/json.hpp>
#include <iostream>
using json = nlohmann::json;
int main() {
std::string json_str = R"({
"labels": [
{
"0": "person",
"1": "helmet",
"2": "clothes",
"3": "smoke",
"4": "phone",
"5": "fire",
"6": "soot"
}
],
"tracks": [
{
"person": {
"attribute": [
"clothes",
"helmet"
],
"other": [
"phone",
"smoke"
]
}
},
{
"scene": {
"safe": [],
"alarm": [
"fire",
"soot"
]
}
}
]
})";
auto j = json::parse(json_str);
// 解析 labels 数组
for (auto& item : j["labels"][0].items()) {
std::cout << item.key() << ": " << item.value() << std::endl;
}
// 解析 tracks 数组
for (auto& item : j["tracks"]) {
if (item.find("person") != item.end()) {
std::cout << "Person: ";
auto& person = item["person"];
std::cout << "Attributes: ";
for (auto& attr : person["attribute"]) {
std::cout << attr << ", ";
}
std::cout << "Other: ";
for (auto& other : person["other"]) {
std::cout << other << ", ";
}
std::cout << std::endl;
} else if (item.find("scene") != item.end()) {
std::cout << "Scene: ";
auto& scene = item["scene"];
std::cout << "Safe: ";
for (auto& safe : scene["safe"]) {
std::cout << safe << ", ";
}
std::cout << "Alarm: ";
for (auto& alarm : scene["alarm"]) {
std::cout << alarm << ", ";
}
std::cout << std::endl;
}
}
return 0;
}
```
输出结果为:
```
0: person
1: helmet
2: clothes
3: smoke
4: phone
5: fire
6: soot
Person: Attributes: clothes, helmet, Other: phone, smoke,
Scene: Safe: , Alarm: fire, soot,
```
这里我们使用json::parse函数将JSON字符串解析为json对象,然后使用auto类型推导来遍历labels和tracks数组中的每个元素,并输出它们的属性值。
在解析tracks数组时,我们先判断它的每个元素是person还是scene类型,并根据不同类型输出它们的属性值。
阅读全文