使用 nlohmann 解析 json 文件
nlohmann 是德国工程师,以其名字为工程名的 nlohmann/json 项目又被成为 JSON for Modern C++。
github文件:https://github.com/nlohmann/json#read-json-from-a-file
nlohmann/json的配置
只需在需要使用的文件中#include“json.hpp”
C++含义
.hpp
,其实质就是将. cpp
的实现代码混入. h
头文件当中,定义与实现都包含在同一文件,则该类的调用者只需要include该hpp
文件即可,无需再
将cpp
加入到project中进行编译。
json基本数据结构
给出相应的json文件
//example.json
{
"pi": 3.141,
"happy": true,
"name": "Niels",
"nothing": null,
"answer": {
"everything": 42
},
"list": [
1,
0,
2
],
"object": {
"currency": "USD",
"value": 42.99
},
"add": 10
}
json文件的读取、构造与输出
#include<iostream>
#include<nlohmann/json.hpp>
#include<fstream>
using json = nlohmann::ordered_json;//这边为按照json文件的实际内容顺序读取