前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用NlohmannJson写JSON保留插入顺序

使用NlohmannJson写JSON保留插入顺序

作者头像
charlee44
发布2020-01-14 11:32:32
3.7K0
发布2020-01-14 11:32:32
举报
文章被收录于专栏:代码编写世界代码编写世界

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。

重新找了一些英文资料,最终找到的解决方案如下:

代码语言:javascript
复制
#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不再是字符串顺序而是插入顺序:

cesium实例位置
cesium实例位置

2. 参考

[1] nlohmann/json主页介绍 [2] nlohmann/json关于保留插入顺序的讨论

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-01-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 正文
  • 2. 参考
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档