C++:使用 nlohmann json 从文件中读取 json 对象

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

我正在使用 nlohmann 的 json 库来处理 c++ 中的 json 对象。最终,我想从文件中读取一个 json 对象,例如像这样的简单对象。

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

我不太确定如何处理这个问题。在 https://github.com/nlohmann 处,给出了几种从字符串文字反序列化的方法,但是将其扩展为在文件中读取似乎并不简单。有人对此有经验吗?

更新 2017-07-03 JSON for Modern C++ version 3

由于 3.0 版json::json(std::ifstream&) 已弃用。应该使用 json::parse() 代替:

std::ifstream ifs("test.json");
json jf = json::parse(ifs);

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

有关如何使用 nlohmann 的 json 库的更多基本信息,请参阅 nlohmann FAQ


更新 JSON 现代 C++ 版本 2

2.0 版json::operator>>() id deprecated。应该使用 json::json() 代替:

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

现代 C++ 版本 1JSON 的原始答案

使用json::operator>>(std::istream&):

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

构造函数 json j(ifs) 已弃用,将在 3.0.0 版中删除。从 2.0.3 版开始你应该这样写:

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