使用 nlohmann C++ 库读取 json 个对象的数组
reading arrays of json objects with nlohmann c++ library
我可以在 nlohmann 库中使用此语法
{
"key1": {"subKey1": "value11",
"subKey2": "value12"},
"key2": {"subKey1": "value21",
"subKey2": "value22"}
}
但我有一个新文件,它也是有效的 json(我检查过)并且是这样写的,它由一个重复对象数组组成。我的代码将需要查看这些对象并分别检查它们内部的值:
[
{"key1": "value11",
"key2": "value12"},
{"key1": "value21",
"key2": "value22"}
]
我曾经这样阅读我的 json 文件:
#include "json.hpp"
nlohmann::json topJson;
nlohmann::json subJson;
if(topJson.find(to_string("key1")) != topJson.end())
{
subJson = topJson["key1"];
entity.SetSubKeyOne(subJson["subKey1"]);
}
但这不适用于我的新文件语法。我怎样才能访问这些重复的对象并告诉 nlohmann 我的对象在一个数组中?更准确地说,我如何能够使用此文件语法达到(例如)“value22”?
谢谢!
你可以试试这个:
std::string ss= R"(
{
"test-data":
[
{
"name": "tom",
"age": 11
},
{
"name": "jane",
"age": 12
}
]
}
)";
json myjson = json::parse(ss);
auto &students = myjson["test-data"];
for(auto &student : students) {
cout << "name=" << student["name"].get<std::string>() << endl;
}
我可以在 nlohmann 库中使用此语法
{
"key1": {"subKey1": "value11",
"subKey2": "value12"},
"key2": {"subKey1": "value21",
"subKey2": "value22"}
}
但我有一个新文件,它也是有效的 json(我检查过)并且是这样写的,它由一个重复对象数组组成。我的代码将需要查看这些对象并分别检查它们内部的值:
[
{"key1": "value11",
"key2": "value12"},
{"key1": "value21",
"key2": "value22"}
]
我曾经这样阅读我的 json 文件:
#include "json.hpp"
nlohmann::json topJson;
nlohmann::json subJson;
if(topJson.find(to_string("key1")) != topJson.end())
{
subJson = topJson["key1"];
entity.SetSubKeyOne(subJson["subKey1"]);
}
但这不适用于我的新文件语法。我怎样才能访问这些重复的对象并告诉 nlohmann 我的对象在一个数组中?更准确地说,我如何能够使用此文件语法达到(例如)“value22”?
谢谢!
你可以试试这个:
std::string ss= R"(
{
"test-data":
[
{
"name": "tom",
"age": 11
},
{
"name": "jane",
"age": 12
}
]
}
)";
json myjson = json::parse(ss);
auto &students = myjson["test-data"];
for(auto &student : students) {
cout << "name=" << student["name"].get<std::string>() << endl;
}