参考链接:Here

什么是nlohman json ?

nlohman json GitHub - nlohmann/json: JSON for Modern C++ 是一个为现代C++(C++11)设计的JSON解析库,主要特点是

  1. 易于集成,仅需一个头文件,无需安装依赖
  2. 易于使用,可以和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;
}

Advanced Sample

示范用法

nlohman::json 库操作的基本对象是 json Object,全部操作围绕此展开

引入代码

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

读取 JSON 文件

#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json; // ... // std::ifstream f("example.json");
std::ifstream f("../config/example.json")
json data = json::parse(f);

从JSON文本创建JSON对象

假设您要在文件中创建此文本 JSON 值作为对象:

{
"pi": 3.141,
"happy": true
}

有多种选择:

// 用原始字符串和json::parse进行初始化
json ex1 = json::parse(R"(
{
"pi": 3.1415,
"happy": true
}
)"); // 用原始字符串和literals进行初始化
using namespace nlohmann::literals;
json ex2 = R"(
{
"pi": 3.141,
"happy": true
}
)"_json; // 使用初始化列表
json ex3 = {
{"happy", true},
{"pi", 3.141},
};

JSON 作为第一类数据类型

下面是一些示例,可让您了解如何使用该类。

假设您要创建 JSON 对象

{
"pi": 3.141,
"happy": true,
"name": "Koshkaaa",
"nothing": null,
"answer": {
"everything": 42
},
"list": [1, 0, 2],
"object": {
"currency": "USD",
"value": 42.99
}
}

使用此库,您可以编写:

// 创建一个空 json 对象 (null)
json j; // 添加一个 double 类型成员
j["pi"] = 3.141; // 添加一个 bool 类型的成员
j["happy"] = true; // 添加一个字符串类型的成员
j["name"] = "Koshkaaa"; // 添加一个空成员
j["nothing"] = nullptr; // 添加一个对象中的对象成员 {"answer":{"everything":42}}
j["answer"]["everything"] = 42; // 添加一个数组对象, 使用 vector
j["list"] = {1,0,2}; // 添加一个对象,使用初始化列表 {"object":{"currency": "USD","value":42.99}}
j["object"] = { {"currency", "USD"}, {"value", 42.99} }; // 也可以一次性写完
json j2 = {
{"pi", 3.141},
{"happy", true},
{"name", "Koshkaaa"},
{"nothing", nullptr},
{"answer", {
{"everything", 42}
}},
{"list", {1, 0, 2}},
{"object", {
{"currency", "USD"},
{"value", 42.99}
}}
};

请注意,在所有这些情况下,您永远不需要“告诉”编译器要使用哪种 JSON 值类型。如果你想明确或表达一些边缘情况,函数json::array()和json::object()会有所帮助:

// 初始化一个空数组对象
json empty_array_explicit = json::array(); // 初始化一个对象
json empty_object_implicit = json({});
json empty_object_explicit = json::object(); // 初始化数组键值对 [["currency", "USD"], ["value", 42.99]]
json array_not_object = json::array({ {"currency", "USD"}, {"value", 42.99} });

序列化/反序列化

json对象和string互转JSON对象和string互转

您可以通过追加到字符串文本来创建 JSON 值(反序列化):_json

// 从字符串创建json对象
json j = "{ \"happy\": true, \"pi\": 3.141 }"_json;
// 使用原始字符串创建json对象
auto j2 = R"(
{
"happy": true,
"pi": 3.141
}
)"_json;

请注意,如果不附加后缀,则传递的字符串文字不会被解析,而只是用作 JSON 字符串 价值。也就是说,只会存储字符串而不是解析实际对象。_jsonjson j = "{ \"happy\": true, \"pi\": 3.141 }""{ "happy": true, "pi": 3.141 }"

上面的例子也可以用json::parse()显式表示:

auto j3 = json::parse(R"({"happy": true, "pi": 3.141})");

获取 JSON 字符串(序列化):

std::string s = j.dump();    // {"happy":true,"pi":3.141}

// 序列化美化json形式
// 传入数字指定缩进空格数
std::cout << j.dump(4) << std::endl;
// {
// "happy": true,
// "pi": 3.141
// }

流输入输出(例如文件读写、字符串流)

您还可以使用流来序列化和反序列化:

// 从标准输入中反序列化
json j;
std::cin >> j; // 序列化到标准输出
std::cout << j; // 美化输出
std::cout << std::setw(4) << j << std::endl;

文件读写json:std::istream,std::ostream

// 读取json文件
std::ifstream i("file.json");
json j;
i >> j; //json对象美化输出到文件
std::ofstream o("pretty.json");
o << std::setw(4) << j << std::endl;

从迭代器范围读取json

可以从迭代器范围解析 JSON;也就是说,从迭代器可访问的任何容器中,迭代器是 1、2 或 4 个字节的整数类型,将分别解释为 UTF-8、UTF-16 和 UTF-32。例如,std::vector<std::uint8_t>,std::list<std::uint16_t>

std::vector<std::uint8_t> v = {'t', 'r', 'u', 'e'};
json j = json::parse(v.begin(), v.end());
std::vector<std::uint8_t> v = {'t', 'r', 'u', 'e'};
json j = json::parse(v);

自定义数据源

由于 parse 函数接受任意迭代器范围,因此您可以通过实现概念来提供自己的数据源。LegacyInputIterator

struct MyContainer {
void advance();
const char& get_current();
}; struct MyIterator {
using difference_type = std::ptrdiff_t;
using value_type = char;
using pointer = const char*;
using reference = const char&;
using iterator_category = std::input_iterator_tag; MyIterator& operator++() {
MyContainer.advance();
return *this;
} bool operator!=(const MyIterator& rhs) const {
return rhs.target != target;
} reference operator*() const {
return target.get_current();
} MyContainer* target = nullptr;
}; MyIterator begin(MyContainer& tgt) {
return MyIterator{&tgt};
} MyIterator end(const MyContainer&) {
return {};
} void foo() {
MyContainer c;
json j = json::parse(c);
}

类似 STL 的访问

我们将 JSON 类设计为类似于 STL 容器的行为。事实上,它满足可逆容器的要求。

// 用push_back创建一个数组对象
json j;
j.push_back("foo");
j.push_back(1);
j.push_back(true); // 使用 emplace_back
j.emplace_back(1.78); // 迭代访问
for (json::iterator it = j.begin(); it != j.end(); ++it) {
std::cout << *it << '\n';
} // 范围迭代
for (auto& element : j) {
std::cout << element << '\n';
} // getter/setter接口
const auto tmp = j[0].get<std::string>();
j[1] = 42;
bool foo = j.at(2); // 比较
j == R"(["foo", 1, true, 1.78])"_json; // true // 其他
j.size(); // 4 个对象
j.empty(); // 是否为空:false
j.type(); // 获取类型:json::value_t::array
j.clear(); // 清空 // 检查类型
j.is_null();
j.is_boolean();
j.is_number();
j.is_object();
j.is_array();
j.is_string(); // 创建一个对象
json o;
o["foo"] = 23;
o["bar"] = false;
o["baz"] = 3.141; // 使用 emplace
o.emplace("weather", "sunny"); // 迭代访问
for (json::iterator it = o.begin(); it != o.end(); ++it) {
std::cout << it.key() << " : " << it.value() << "\n";
} // 循环访问
for (auto& el : o.items()) {
std::cout << el.key() << " : " << el.value() << "\n";
} // 匿名对象迭代器(C++17)
for (auto& [key, value] : o.items()) {
std::cout << key << " : " << value << "\n";
} // 查找key
if (o.contains("foo")) {
// 找到foo的键值
} // 通过迭代器查找
if (o.find("foo") != o.end()) {
// 找到foo的键值
} // 用count()统计是否有键值
int foo_present = o.count("foo"); // 1
int fob_present = o.count("fob"); // 0 // 删除foo对象
o.erase("foo");

从 STL 容器转换

从STL容器转换到json,std::list转json,std::vector转json

std::vector<int> c_vector {1, 2, 3, 4};
json j_vec(c_vector);
// [1, 2, 3, 4] std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};
json j_deque(c_deque);
// [1.2, 2.3, 3.4, 5.6] std::list<bool> c_list {true, true, false, true};
json j_list(c_list);
// [true, true, false, true] std::forward_list<int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};
json j_flist(c_flist);
// [12345678909876, 23456789098765, 34567890987654, 45678909876543] std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};
json j_array(c_array);
// [1, 2, 3, 4] std::set<std::string> c_set {"one", "two", "three", "four", "one"};
json j_set(c_set); // only one entry for "one" is used
// ["four", "one", "three", "two"] std::unordered_set<std::string> c_uset {"one", "two", "three", "four", "one"};
json j_uset(c_uset); // only one entry for "one" is used
// maybe ["two", "three", "four", "one"] std::multiset<std::string> c_mset {"one", "two", "one", "four"};
json j_mset(c_mset); // both entries for "one" are used
// maybe ["one", "two", "one", "four"] std::unordered_multiset<std::string> c_umset {"one", "two", "one", "four"};
json j_umset(c_umset); // both entries for "one" are used
// maybe ["one", "two", "one", "four"]

std::mapjsonstd::unorderedjson

std::map<std::string, int> c_map { {"one", 1}, {"two", 2}, {"three", 3} };
json j_map(c_map);
// {"one": 1, "three": 3, "two": 2 } std::unordered_map<const char*, double> c_umap { {"one", 1.2}, {"two", 2.3}, {"three", 3.4} };
json j_umap(c_umap);
// {"one": 1.2, "two": 2.3, "three": 3.4} std::multimap<std::string, bool> c_mmap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
json j_mmap(c_mmap); // only one entry for key "three" is used
// maybe {"one": true, "two": true, "three": true} std::unordered_multimap<std::string, bool> c_ummap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
json j_ummap(c_ummap); // only one entry for key "three" is used
// maybe {"one": true, "two": true, "three": true}

【3rd Party】nlohmann json 基础用法的更多相关文章

  1. json基础用法

    JSON格式 JSON格式(JavaScript Object Notation的缩写)是一种用于数据交换的文本格式,2001年由Douglas Crockford提出,目的是取代繁琐笨重的XML格式 ...

  2. elasticsearch安装与基础用法

    来自官网,版本为2.3 注意elasticsearch依赖jdk,2.3依赖jdk7 下载rpm包并安装 wget -c https://download.elastic.co/elasticsear ...

  3. Docker基础用法篇

    Docker基础用法篇 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.安装docker 1>.依赖的基础环境 64 bits CPU Linux Kerner 3.10+ ...

  4. PropertyGrid控件由浅入深(二):基础用法

    目录 PropertyGrid控件由浅入深(一):文章大纲 PropertyGrid控件由浅入深(二):基础用法 控件的外观构成 控件的外观构成如下图所示: PropertyGrid控件包含以下几个要 ...

  5. json基础

    1 xml缺点 用xml表示一个对象,数据存储效率低 <person> <firstName>Morra<firstName> <lastName>Do ...

  6. 再谈Newtonsoft.Json高级用法

    上一篇Newtonsoft.Json高级用法发布以后收到挺多回复的,本篇将分享几点挺有用的知识点和最近项目中用到的一个新点进行说明,做为对上篇文章的补充. 阅读目录 动态改变属性序列化名称 枚举值序列 ...

  7. 【Java EE 学习 31】【JavaScript基础增强】【Ajax基础】【Json基础】

    一.JavaScript基础增强 1.弹窗 (1)使用window对象的showModelDialog方法和showModelessDialog方法分别可以弹出模式窗口和非模式窗口,但是只能在IE中使 ...

  8. logstash安装与基础用法

    若是搭建elk,建议先安装好elasticsearch 来自官网,版本为2.3 wget -c https://download.elastic.co/logstash/logstash/packag ...

  9. BigDecimal最基础用法

    BigDecimal最基础用法 用字符串生成的BigDecimal是不会丢精度的. 简单除法. public class DemoBigDecimal { public static void mai ...

  10. JSON基本用法

    JSON基本用法 2016-08-10 16:42:19   JSON的全称是“JavaScript Object Notation”,意思是JavaScript对象表示法,它是一种基于文本,独立于语 ...

随机推荐

  1. [ORB/BEBLID] 利用OpenCV(C++)实现尺度不变性与角度不变性的特征找图算法

    本文只发布于利用OpenCV实现尺度不变性与角度不变性的特征找图算法和知乎 一般来说,利用OpenCV实现找图功能,用的比较多的是模板匹配(matchTemplate).笔者比较喜欢里面的NCC算法. ...

  2. C#12中的Collection expressions(集合表达式语法糖)

    C#12中引入了新的语法糖来创建常见的集合.并且可以使用..来解构集合,将其内联到另一个集合中. 支持的类型 数组类型,例如 int[]. System.Span<T> 和 System. ...

  3. OpenAI 董事会宫斗始作俑者?一窥伊尔亚·苏茨克维内心世界

    OpenAI 董事会闹剧应该是暂告一个段落了,Sam Altman和Greg Brockman等一众高管均已加入微软,还有员工写联名信逼宫董事会的戏码,关注度已经降下来了. 但是,这场宫斗闹剧的中心人 ...

  4. list.add()语句作用

    ----该方法用于向集合列表中添加对象 示例  本示例使用List接口的实现类ArrayList初始化一个列表对象,然后调用add方法向该列表中添加数据. public static void mai ...

  5. 在模态窗口中控制窗口的隐藏和显示(.NET)

    如果你创建了模态窗口,虽然一些API,例如Editor.GetSelection(),可以自动隐藏模式对话框,但如果从模态窗口出发与编辑器(编辑器指的模型空间,即你绘图的窗口)交互, 它会在GetSe ...

  6. Diffusion Model扩散模型

    1.扩散模型基本原理: 扩散模型包括两个步骤: 固定的(或预设的)前向扩散过程q:该过程会逐渐将高斯噪声添加到图像中,直到最终得到纯噪声. 2.可训练的反向去噪扩散过程pθ:训练一个神经网络,从纯噪音 ...

  7. 蓝桥杯-最短路 (SPFA算法学习)

    SPFA算法主要用来解决存在负边权的单源最短路情况(但不能有负环!!!)一个简单的方法判断是否有没有负环可以通过判断是否有一个节点是否频繁进出队列. 以下内容转自https://blog.csdn.n ...

  8. 组合式api-侦听器watch的语法

    和vue2对比,也是语法上稍有不同. 监听单个数据对象 <script setup> import {ref, watch} from "vue"; const cou ...

  9. MyBatis高频面试题

    1.MyBatis中使用#和$书写占位符有什么区别? 2.Hibernate 与 Mybatis区别(MyBatis与Hibernate有什么不同). 3.持久层设计要考虑的问题有哪些? 4.你用过的 ...

  10. parameterType的用法

    在mybatis映射接口的配置中,有select,insert,update,delete等元素都提到了parameterType的用法,parameterType为输入参数,在配置的时候,配置相应的 ...