Search code examples
c++jsonnlohmann-json

Reading Items inside of an array in an array C++


I have a very quick question...

I'm using nlohmann's json library.

My issue is that when I go to print a element, the program stops responding.

My json file

{
  "Consoleprinting": false,
  "Input" : [{"Code" : [{"Name": "EC", "Keybind": "VK_NUMPAD1"}] }]
}

What I have tried.

nlohmann::json jsonData = nlohmann::json::parse(i_Read);

std::cout << jsonData << std::endl;

for (auto& array : jsonData["Input"]) {
    std::cout << array["Code"] << std::endl;
}

^ This works but it prints out

[{"Name": "EC", "Keybind": "VK_NUMPAD1"}]

How can I get this it print out just the name?


Solution

  • array["Code"] is an array containing a single collection of key-value pairs, so you need to write:

    std::cout << array["Code"][0]["Name"] << std::endl;