当前位置: 首页 > article >正文

C++ nlohmann json库快速使用

前言

C++ nlohmann/json 库是一个非常易用,高性能的 json 库。

CMake FetchContent方式集成

include(FetchContent)  
FetchContent_Declare(json  
        URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz)  
FetchContent_MakeAvailable(json)  
  
target_link_libraries(json_demo PRIVATE nlohmann_json::nlohmann_json)

快速使用

包含头文件以及声明命名空间别名:

#include <nlohmann/json.hpp>
using json = nlohmann::json;

解析json

从文件读取解析
// method 1
std::ifstream f("example.json");
json data = json::parse(f);

// method 2
std::ifstream i("file.json");
json j;
i >> j;
从字符串读取解析
// Using (raw) string literals and json::parse
json ex1 = json::parse(R"(
  {
    "pi": 3.141,
    "happy": true
  }
)");

// Using user-defined (raw) string literals
using namespace nlohmann::literals;
json ex2 = R"(
  {
    "pi": 3.141,
    "happy": true
  }
)"_json;

// Using initializer lists
json ex3 = {
  {"happy", true},
  {"pi", 3.141},
};

遍历

// special iterator member functions for objects
for (json::iterator it = o.begin(); it != o.end(); ++it) {
  std::cout << it.key() << " : " << it.value() << "\n";
}

// the same code as range for
for (auto& el : o.items()) {
  std::cout << el.key() << " : " << el.value() << "\n";
}

// even easier with structured bindings (C++17)
for (auto& [key, value] : o.items()) {
  std::cout << key << " : " << value << "\n";
}

查找 Key

if (j.contains("key")) {
}

if (j.find("foo") != o.end()) {
}

读取 key

auto value = j["key"];
auto value = j.at("key");
std::string value = j["key"].template get<std::string>();

// C++17 
using namespace std::literals;
// 如果key不存在,则返回默认值0
int v_integer = j.value("integer"sv, 0); 

删除 key

// delete an entry
o.erase("foo");

注意:数组可能无法删除单个元素

写入 json 文件

std::ofstream o("pretty.json");
o << std::setw(4) << j << std::endl;

序列化设置缩进

// 按照四个空格缩进打印json
std::cout << j.dump(4) << std::endl;

总结

以上就是在使用 json 库时的常用场景。

https://github.com/nlohmann/json

https://github.com/nlohmann/json/tree/develop/docs/examples


http://www.kler.cn/news/336005.html

相关文章:

  • 动手学深度学习(李沐)PyTorch 第 5 章 深度学习计算
  • 120页PPT企业对标管理指导:对标具有全球竞争力的世界一流企业
  • 深度学习中的损失函数详解
  • C++ | Leetcode C++题解之第459题重复的子字符串
  • TI DSP TMS320F280025 Note15:串口SCI的使用
  • 舵机驱动详解(模拟/数字 STM32)
  • 关于vscode中settings.json中的设置
  • QT使用qss控制样式实现动态换肤
  • 安装最新 MySQL 8.0 数据库(教学用)
  • Spring Boot实现新闻个性化推荐
  • 每日一题——第一百一十一题
  • Vue.js 组件开发详解
  • [C#]winform部署官方yolov11-obb旋转框检测的onnx模型
  • Redis操作常用API
  • 【机器学习】知识总结1(人工智能、机器学习、深度学习、贝叶斯、回归分析)
  • windows环境下使用socket进行tcp通信
  • .NET NoSQL 嵌入式数据库 LiteDB 使用教程
  • Unity3D播放GIF图片 插件播放
  • springboot工程中使用tcp协议
  • LeetCode 209 Minimum Size Subarray Sum 题目解析和python代码