对于如下json文件:
{
"cars_list":[{
"color": "green",
"name": "benz",
"type": "saloon"
},
{
"color": "red",
"name": "BMW",
"type": "saloon"
},
{
"color": "blue",
"name": "Lamborghini",
"type": "sports"
}
]
}
如果我只想拿出其中的name属性:
void json_test()
{
std::string fileName = "./test.json";
std::string fileStr = readFile(fileName);//将json读成string
nlohmann::json json_t = nlohmann::json::parse(fileStr);//解析string
for (auto &value : json_t["cars_list"])//遍历cars_list的value
{
std::string name = value["name"];
std::cout<<"name:"<<name<<std::endl;
}
}
std::string readFile(std::string fileName)
{
std::ifstream myfile;
myfile.open(fileName, std::ios::in | std::ios::binary);
string content((istreambuf_iterator<char>(myfile)),(istreambuf_iterator<char>()));
myfile.close();
return content;
}