使用nlohmann c ++库读取json对象的数组

问题描述

我可以在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;
}