使用NlohmannJson写JSON保留插入顺序
1. 正文
nlohmann/json是一个C++的读写JSON的组件,号称使用现代C++范式写的。简单看了一下,这个组件确实包含了很多cpp11以上的特性,在vs2015及一下的版本甚至没办法正常编译。要正常使用需要vs2017及以上版本才行。
在使用过程中,遇到了一个问题是没办法保持插入的顺序,每个插入的键值对会按照字符串的顺序排列的,因为其内部用到了std:map。查看了github的主页说明,是这么说的:
By default, the library does not preserve the insertion order of object elements. This is standards-compliant, as the JSON standard defines objects as "an unordered collection of zero or more name/value pairs". If you do want to preserve the insertion order, you can specialize the object type with containers like tsl::ordered_map (integration) or nlohmann::fifo_map (integration).
这段话的意思是JSON标准的定义是零个或多个键值对对的无序集合,如果要保证插入顺序,可以使用tsl::ordered_map(integration)或nlohmann::fifo_map(integration)等容器专门化对象类型。nlohmann::fifo_map同样在github上找到,“专门化对象类型”的意思是nlohmann/json组件内部用到了很多std容器,只需要将其替换成可以保存插入顺序的容器就可以了,也就是nlohmann::fifo_map。
重新找了一些英文资料,最终找到的解决方案如下:
#include "json.hpp"
#include "fifo_map.hpp"
#include <iostream>
using namespace nlohmann;
// A workaround to give to use fifo_map as map, we are just ignoring the 'less' compare
template<class K, class V, class dummy_compare, class A>
using my_workaround_fifo_map = fifo_map<K, V, fifo_map_compare<K>, A>;
using my_json = basic_json<my_workaround_fifo_map>;
int main()
{
my_json j;
j["f"] = 5;
j["a"] = 2;
my_json j2 = {
{"pi", 3.141},
{"happy", true},
{"name", "Niels"},
{"nothing", nullptr},
{"answer", {
{"everything", 42}
}},
{"list", {1, 0, 2}},
{"object", {
{"currency", "USD"},
{"value", 42.99}
}}
};
std::cout << j.dump(4) << std::endl;
std::cout << j2.dump(4) << std::endl;
return 0;
}
运行结果如下所示,可以看到输出的JSON不再是字符串顺序而是插入顺序:

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了