user3515814 user3515814 - 1 year ago 758
JSON Question

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

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 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?

Answer Source

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

json j;
std::ifstream ifs("test.json");
ifs >> j;

Since version 2.0, one could write:

std::ifstream ifs("test.json");
json j(ifs);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download