accessing elements from nlohmann json

The following link explains the ways to access elements in the JSON. In case the link goes out of scope here is the code

#include <json.hpp>

 using namespace nlohmann;

 int main()
 {
     // create JSON object
     json object =
     {
         {"the good", "il buono"},
         {"the bad", "il cativo"},
         {"the ugly", "il brutto"}
     };

     // output element with key "the ugly"
     std::cout << object.at("the ugly") << '\n';

     // change element with key "the bad"
     object.at("the bad") = "il cattivo";

     // output changed array
     std::cout << object << '\n';

     // try to write at a nonexisting key
     try
     {
         object.at("the fast") = "il rapido";
     }
     catch (std::out_of_range& e)
     {
         std::cout << "out of range: " << e.what() << '\n';
     }
 }

I really like to use this in C++:

for (auto& el : object["list1"].items())
{
  std::cout << el.value() << '\n';
}

It will loop over the the array.


In case anybody else is still looking for the answer.. You can simply access the contents using the same method as for writing to an nlohmann::json object. For example to get values from json in the question:

{
  "active" : false,
  "list1" : ["A", "B", "C"],
  "objList" : [
    {
      "key1" : "value1",
      "key2" : [ 0, 1 ]
    }
  ]
}

just do:

nlohmann::json jsonData = nlohmann::json::parse(your_json);
std::cout << jsonData["active"] << std::endl;    // returns boolean
std::cout << jsonData["list1"] << std::endl;     // returns array

If the "objList" was just an object, you can retrieve its values just by:

std::cout << jsonData["objList"]["key1"] << std::endl;    // returns string
std::cout << jsonData["objList"]["key2"] << std::endl;    // returns array

But since "objList" is a list of key/value pairs, to access its values use:

for(auto &array : jsonData["objList"]) {
    std::cout << array["key1"] << std::endl;    // returns string
    std::cout << array["key2"] << std::endl;    // returns array
}

The loop runs only once considering "objList" is array of size 1.

Hope it helps someone

Tags:

C++

Json