当前位置: 代码网 > it编程>编程语言>Javascript > C++ nlohmann/json库怎么用?从解析到写入的完整教程

C++ nlohmann/json库怎么用?从解析到写入的完整教程

2026年09月13日 Javascript 我要评论
前言c++ nlohmann/json 库是一个非常易用,高性能的 json 库。cmake fetchcontent方式集成include(fetchcontent) fetchcontent_d

前言

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 库时的常用场景。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com