什么是nlohman json ?
nlohman json GitHub - nlohmann/json: JSON for Modern C++ 是一个为现代C++(C++11)设计的JSON解析库,主要特点是
- 易于集成,仅需一个头文件,无需安装依赖
- 易于使用,可以和STL无缝对接,使用体验近似python中的json
Minimal Example
CMakeLists.txt 编写教程:Here
# CMakeLists.txt
cmake_minimum_required(VERSION 3.24)
project(nlohmannJson)
set(CMAKE_CXX_STANDARD 17)
include_directories("include")
add_executable(${PROJECT_NAME} src/main.cpp)
// main.cpp
#include <iostream>
#include "nlohmann/json.hpp"
using namespace std;
using namespace nlohmann;
int main() {
auto config_json = json::parse(R"({"Happy": true, "pi": 3.1415})");
cout << config_json << endl;
return 0;
}
示范用法
nlohman::json
库操作的基本对象是 json Object
,全部操作围绕此展开
更多示例在 GitHub - nlohmann/json: JSON for Modern C++
从文件读取json信息
// read json from file
std::ifstream input_json_file("../configs/config.json");
nlohmann::json config_json;
input_json_file >> config_json;
从字符串中读取json信息
// from string, just use _json
auto config_json = R"({"A" : "a", "B" : "b", "Pi" : 1234 })"_json;
// parse explicitly
std::string info = R"({"A" : "a", "B" : "b", "Pi" : 1234 })";
auto config_json = nlohmann::json::parse(info);
直接创建json对象
json j1 = {
{"pi", 3.141},
{"happy", true},
{"name", "Niels"},
{"nothing", nullptr},
{"answer", {
{"everything", 42}
}},
{"list", {1, 0, 2}},
{"object", {
{"currency", "USD"},
{"value", 42.99}
}}
};
json j2; // create null object
j2["pi"] = 3.1415;
j2["list"] = {1,2,3,4,5};
j2["object"] = { {"currency", "USD"}, {"value", 42.99} };
从json对象获取键值对
auto config_json = R"({"A" : "a", "B" : "b", "Pi" : 1234 })"_json;
// 遍历键值对
for(auto elem : config_json.items()){
std::cout << elem.key() << " , " << elem.value() << std::endl;
}
// C++ 17
for (auto& [key, value] : j1.items()) {
cout << key << " : " << value << "\n";
}
// 直接访问
std::string s1 = config_json["a"];
和std::vector交互
json j1 = {
{"list", {1, 0, 2}},
{"object", {
{"currency", "USD"},
{"value", 42.99}
}}
};
std::vector<int> a = j1["list"];
for (auto& elem : a){
cout << elem << endl;
}
// output
//1
//0
//2
json j2;
j2["vector"] = a;
std::vector<string> b{"s1","s2","s3"};
j2["string vector"] = b;
cout << j2;
// output
// {"string vector":["s1","s2","s3"],"vector":[1,0,2]}
序列化
auto j = json::parse(R"({"happy": true, "pi": 3.141})")
// 写入字符串
std::string s = j.dump();
// 写入文件
std::ofstream o("pretty.json");
o << j << "\n;