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

JCS*_*CSB 5 c++ arrays json nlohmann-json

我可以在 nlohmann 库中使用此语法

{
 "key1": {"subKey1": "value11", 
          "subKey2": "value12"},
 "key2": {"subKey1": "value21", 
          "subKey2": "value22"}
}
Run Code Online (Sandbox Code Playgroud)

但我有一个新文件,它也是有效的 json (我检查过)并且是这样编写的,它由重复对象的单个数组组成。我的代码需要查看这些对象并单独检查它们内部的值:

[
 {"key1": "value11", 
  "key2": "value12"},
 {"key1": "value21", 
  "key2": "value22"}
]
Run Code Online (Sandbox Code Playgroud)

我曾经这样读取我的 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"]);
    }
Run Code Online (Sandbox Code Playgroud)

但这不适用于我的新文件语法。我如何访问这些重复的对象并告诉 nlohmann 我的对象位于数组内?更准确地说,我如何能够使用此文件语法达到(例如)“value22”?

谢谢!

gar*_*133 3

你可以试试这个:

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;
}
Run Code Online (Sandbox Code Playgroud)