我正在使用NLHHMAN的JSON库来与C++中的JSON对象一起工作.最后,我想从一个文件中读取一个json对象,例如这样一个简单的对象.

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

推荐答案

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);

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


Update for JSON for Modern C++ version 2

version 2.0年到json::operator>>() id deprecated年.人们应该使用json::json()来代替:

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

Original answer for JSON for Modern C++ version 1

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

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

Json相关问答推荐

抓取低于w jolt的对象级别

在解码的JSON哈希中搜索数组元素

处理输入数据并转换为更简单的格式-PowerBI

集成wix.comstore API|变音符号问题

在深度嵌套数组中使用布尔属性的jq-select

用巨大的值更新SQL Server中的nvarchar(max)

Delphi 11.3无法从变体创建/添加JSON

JOLT转换并向输出添加新数组

将JSON行转换为TSV格式, for each 数组项生成单独的行

jq - 仅在键值对存在的地方打印值

try 使用 JQ 转换 JSON 中过于复杂的对象数组

为什么根据其他工具,来自 aws rds 的 JSON 在 Docker 中格式错误运行?

使用 BASH 和 JQ 我想将 json 文件与 bash 数组进行比较

Qt使用QJsonDocument、QJsonObject、QJsonArray解析JSON

在 JSON API Wordpress 上启用 CORS

谷歌浏览器不允许我放置断点

在 Jersey 服务中使用 JSON 对象

我应该如何处理 JSON 中的 HATEOAS 链接和引用?

在 Android 中使用带有 post 参数的 HttpClient 和 HttpPost

你如何在 Arrays of Arrays 上 OPENJSON