C ++:使用nlohmann json从文件中读取json对象 [英] C++: Reading a json object from file with nlohmann json

查看:1227
本文介绍了C ++:使用nlohmann json从文件中读取json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用nlohmann的json库在c ++中处理json对象.最终,我想从文件中读取一个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
}

我不太确定该如何处理.在 https://github.com/nlohmann 处,给出了几种从字符串文字反序列化的方法,但实际上并没有.将其扩展为读取文件似乎微不足道.有人对此有经验吗?

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?

推荐答案

2017年3月3日更新 适用于现代C ++版本3的JSON

版本3.0 起,不推荐使用json::json(std::ifstream&).人们应该使用

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("{\"json\": true}");
json j = json::parse(ifs);


JSON for Modern C ++ version 2的更新

版本2.0 起,


Update for JSON for Modern C++ version 2

Since version 2.0, json::operator>>() id deprecated. One should use json::json() instead:

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


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

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


Original answer for JSON for Modern C++ version 1

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

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

这篇关于C ++:使用nlohmann json从文件中读取json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆