C++: Reading a json object from file with nlohmann json

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("test.json");
json jf = json::parse(ifs);

std::string str(R"({"json": "beta"})");
json js = json::parse(str);

For more basic information on how to use nlohmann's json library, see nlohmann FAQ.


Update for JSON for Modern C++ version 2

Since version 2.0, json::operator>>() id deprecated. One should use json::json() instead:

std::istringstream ifs("{\"json\": true}");
json j(ifs);

Original answer for JSON for Modern C++ version 1

Use json::operator>>(std::istream&):

json j;
std::stringstream 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);