Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get array from nlohmann json

Tags:

c++

json

I tried to search how to get array from json using JSON for Modern C++, but I couldn't find answer.

I have json like this:

{
  "Command": "cmd",
  "Data":{"time": 200, "type":1},
  ...
}

And I want to ask how to get object with key "Data", how to store it and how to access it's elements (count of elements and keys in data can change depending on command).

Thanks for help

like image 400
kubeks2001 Avatar asked Mar 19 '17 13:03

kubeks2001


People also ask

How do I get JSON data into an array?

Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.

How can we get JSON array from JSON string?

String value = (String) jsonObject. get("key_name"); Just like other element retrieve the json array using the get() method into the JSONArray object.

Can we convert JSON to array?

Convert JSON to Array Using `json. The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string. Make sure that it has a string value coming from a server or the local source.

Can JSON parse array?

Use the JSON. parse() method to pase a JSON array, e.g. JSON. parse(arr) . The method parses a JSON string and returns its JavaScript value or object equivalent.


1 Answers

You can read a json file into a json object like that:

std::ifstream jsonFile("commands.json");
nlohmann::json commands;
jsonFile >> commands;

To retrieve the "Data" object (and print the number of elements it contains):

nlohmann::json data = commands["Data"];
std::cout << "Number of items in Data: " << data.size() << std::endl;

And finally to loop over all keys and values in "Data":

for (auto it = data.begin(); it != data.end(); ++it)
{
    std::cout << it.key() << ": " << it.value() << std::endl;
}
like image 143
inabout Avatar answered Sep 28 '22 11:09

inabout