Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Using nlohmann json now, I've managed to store it and when I do a dump
jsonRootNode.dump()
, the contents are represented properly.
However I can't find a way to access the contents.
I've tried
jsonRootNode["active"]
,
jsonRootNode.get()
and using the
json::iterator
but still can't figure out how to retrieve my contents.
I'm trying to retrieve
"active"
, the array from
"list1"
and object array from
"objList"
–
–
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
object.at("the fast") = "il rapido";
catch (std::out_of_range& e)
std::cout << "out of range: " << e.what() << '\n';
–
–
–
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
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.