I am using the nlohmann's json library to work with json objects in c++. Ultimately, I'd like to read a json object from a file, e.g. a simple object like this.
{
"happy": true,
"pi": 3.141
}
I'm not quite sure how to approach this. At https://github.com/nlohmann several ways are given to deserialise from a string literal, however it doesn't seem trivial to extend this to read in a file. Does anyone have experience with this?
Update 2017-07-03 for JSON for Modern C++ version 3
Since version 3.0, json::json(std::ifstream&)
is deprecated. One should use json::parse()
instead:
std::ifstream ifs("{\"json\": true}");
json j = json::parse(ifs);
Update for JSON for Modern C++ version 2
Since version 2.0, json::operator>>() id deprecated
. One should use json::json()
instead:
std::ifstream ifs("{\"json\": true}");
json j(ifs);
Original answer for JSON for Modern C++ version 1
Use json::operator>>(std::istream&)
:
json j;
std::ifstream ifs("{\"json\": true}");
ifs >> j;
The constructor json j(ifs)
is deprecated and will be removed in version 3.0.0. Since version 2.0.3 you should write:
std::ifstream ifs("test.json");
json j = json::parse(ifs);
来源:https://stackoverflow.com/questions/33628250/c-reading-a-json-object-from-file-with-nlohmann-json