C ++: reading json object from file with nlohmann json

I am using the nlohmann json library to work with json objects in C ++. Ultimately, I would like to read a json object from a file, for example. a simple object like this.

{ "happy": true, "pi": 3.141 } 

I'm not quite sure how to approach this. There are several ways to deserialize from a string literal at https://github.com/nlohmann , however it does not seem trivial to read to a file. Does anyone have any experience?

+8
source share
2 answers

Update 2017-07-03 for JSON for Modern C ++ version 3

Starting with version 3.0, json::json(std::ifstream&) deprecated. Instead, use json::parse() :

 std::ifstream ifs("{\"json\": true}"); json j = json::parse(ifs); 

JSON Update for Modern C ++ Version 2

Starting with version 2.0, json::operator>>() id deprecated . Instead, use json::json() :

 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; 
+17
source

The json j(ifs) constructor is deprecated and will be removed in version 3.0.0. Starting with version 2.0.3 you should write:

 std::ifstream ifs("test.json"); json j = json::parse(ifs); 
+2
source

Source: https://habr.com/ru/post/1235608/


All Articles