38

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?

YSC
  • 38,212
  • 9
  • 96
  • 149
user3515814
  • 957
  • 2
  • 8
  • 13

2 Answers2

79

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;
Bklyn
  • 2,559
  • 2
  • 20
  • 16
YSC
  • 38,212
  • 9
  • 96
  • 149
  • 9
    Hi there, for version 2.0.0, I added a constructor to cope with an input stream directly, so you could write `json j(ifs);`. See http://nlohmann.github.io/json/classnlohmann_1_1basic__json_a9857835334d38ba04959e348ca6be208.html#a9857835334d38ba04959e348ca6be208 for more details. – Niels Lohmann Feb 05 '16 at 19:23
  • Do you have to close the ifstream to prevent memory leaks? – IntegrateThis Jun 13 '22 at 05:02
  • @IntegrateThis No - the `ifstream` closes the stream when it goes out of scope. Manually closing `*fstream`s is rarely done. Only if you want to `close` and then `open` something else using the same `*fstream`. – Ted Lyngmo Aug 31 '22 at 21:04
  • What about enabling exception handling on the `std::ifstream` to figure out if the file was successfully opened and read? – BullyWiiPlaza May 21 '23 at 23:49
  • @YSC: It would be better to enable exceptions to catch errors regarding loading from the file I suppose, right? – BullyWiiPlaza May 27 '23 at 16:18
  • This is far (faaar) beyond the scope of the question. – YSC May 27 '23 at 22:13
14

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);
Markus
  • 149
  • 1
  • 8