title: c++ nlohman/json库
top: 42
date: 2024-06-06 17:09:54
tags:
- c++
- json
categories: - nlohman/json
-
nlohman/json
是一个方便易用的C++ json解析库。它是一个开源项目,GitHub地址 -
在使用时,你只需要引入头文件
nlohmann/json.hpp
C++ code
#include <iostream>
#include <fstream>
#include <typeinfo>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
using std::cout;
using std::endl;
int load()
{
std::ifstream fr {R"(D:/documents/lang/test_nlohman/hs_probe.json)"};
if (!fr)
{
std::cerr << "ERROR: Open file failed." << std::endl;
return 1;
}
json data = json::parse(fr);
std::cout << data["path"][0].get<std::string>() << std::endl;
cout << data["path"].is_array() << endl;
cout << data["path"][0].is_string() << endl;
cout << typeid(data["path"][0].get<std::string>()).name() << endl;
return 0;
/* stdout
adder_2stage_with_reset
1
1
class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
*/
}
int dump()
{
std::ofstream fw {R"(D:/documents/lang/test_nlohman/dump.json)"};
if (!fw.is_open())
{
std::cerr << "ERROR: Open file failed." << std::endl;
return 1;
}
json dump;
dump["instance_name"] = "";
dump["member"] = NULL;
dump["module_name"] = "adder_2stage_with_reset";
dump["path"] = {"adder_2stage_with_reset"};
dump["signal"] = {{{"direction", "INPUT"},{"name", "A"}}};
json sig;
sig["direction"] = "INPUT";
sig["name"] = "B";
dump["signal"].push_back(sig);
fw << std::setw(2)<<dump; // std::setw(2) format json by 2 space
fw.close();
return 0;
/* content in file dump.json
{
"instance_name": "",
"member": 0,
"module_name": "adder_2stage_with_reset",
"path": [
"adder_2stage_with_reset"
],
"signal": [
{
"direction": "INPUT",
"name": "A"
},
{
"direction": "INPUT",
"name": "B"
}
]
}
*/
}
int main() {
load();
dump();
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.23)
project(test_nlohman)
set(CMAKE_CXX_STANDARD 17)
include_directories(C:/Users/bgape/Desktop/json-develop/include)
# include_directories(C:/Users/bgape/Desktop/json-develop/single_include)
add_executable(test_nlohman main.cpp)