Search code examples
c++arraysjsonnlohmann-json

reading arrays of json objects with nlohmann c++ library


I am ok using this syntax with the nlohmann library

{
 "key1": {"subKey1": "value11", 
          "subKey2": "value12"},
 "key2": {"subKey1": "value21", 
          "subKey2": "value22"}
}

But I have a new file, which is valid json too (I checked) and is written this way, it is made of a single array of repetitive objects. My code will require to look through those objects and check values inside them individually:

[
 {"key1": "value11", 
  "key2": "value12"},
 {"key1": "value21", 
  "key2": "value22"}
]

I used to read my json files this way:

  #include "json.hpp"
  
  nlohmann::json topJson;
  nlohmann::json subJson;

    if(topJson.find(to_string("key1")) != topJson.end())
    {
        subJson = topJson["key1"]; 
        entity.SetSubKeyOne(subJson["subKey1"]);
    }

But this won't work with my new file syntax. How can I access these repetitive objects and tell nlohmann that my objects are inside an array? More precisely, how would I be able to reach (for example) "value22" with this file syntax?

Thanks!


Solution

  • You can try this:

    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;
    }