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
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.
String value = (String) jsonObject. get("key_name"); Just like other element retrieve the json array using the get() method into the JSONArray object.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With