c++使用nlohmann读取json文件

下载:

GitHub - nlohmann/json: JSON for Modern C++

 解压:

包含头文件:

要包含的头文件和要使用的命名空间:

#include <nlohmann/json.hpp>

using json = nlohmann::json;

测试文件:

代码:

#include <iostream>
#include <fstream>
#include <string>
#include <nlohmann/json.hpp>
using namespace std;
using json = nlohmann::json;
void demo01() {
	string path = "D:\\ALearn\\read_json\\testJsonFile\\1.json";
	ifstream file(path);
	json j;
	//>> 运算符被重载为从 file 中读取数据,并将其解析为 JSON 格式,存储到 j 对象中
	file >> j;
	json j2 = j["a"];
	cout << j2["A"] << endl; cout << j2["B"] << endl;
	json j3 = j2["C"];
	cout << j3["a"] << endl; cout << j3["b"] << endl;
	//数组
	for (const auto& tmp : j3) {
		//可以用if判断解决数字和字符串
		cout << "arr: " << tmp << endl;
	}
}
int main() {
	demo01();
}

运行截图:

注意:文件编码格式不对会报错,像下面这样:

中文乱码我还不会解决!!!!

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值