You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用nlohmann::json按指定顺序输出JSON字符串?

问题:nlohmann::json 如何按指定顺序输出JSON字符串

我在C++中使用nlohmann::json库,执行以下代码:

nlohmann::json msg_j = "{\"H\":\"1\",\"N\":3,\"D1\":3,\"D2\":150}"_json; 
std::string s = msg_j.dump();

得到的结果s为:

{"D1":3,"D2":150,"H":"1","N":3}

但我期望的顺序是:

{"H":"1","N":3,"D1":3,"D2":150}

请问如何实现按指定顺序输出JSON字符串?


解决方法

nlohmann::json的默认实现不保证JSON对象键的输出顺序,因为它内部使用无序容器存储键值对。要按指定顺序输出,你可以使用以下方式:

1. 使用nlohmann::ordered_json类型

ordered_json是库提供的有序JSON类型,会严格保留键的插入/解析顺序。直接替换默认的json类型即可:

nlohmann::ordered_json msg_j = "{\"H\":\"1\",\"N\":3,\"D1\":3,\"D2\":150}"_json; 
std::string s = msg_j.dump();

执行后s的内容会和你期望的顺序一致。

2. 手动按顺序构造JSON对象

如果是自己构建JSON而非解析字符串,按目标顺序逐个添加键值对(同样使用ordered_json):

nlohmann::ordered_json msg_j;
msg_j["H"] = "1";
msg_j["N"] = 3;
msg_j["D1"] = 3;
msg_j["D2"] = 150;
std::string s = msg_j.dump();

3. 转换已有默认JSON对象为有序类型

如果已经有一个默认的nlohmann::json对象,可以将其转换为ordered_json来保证顺序:

nlohmann::json original_j = "{\"H\":\"1\",\"N\":3,\"D1\":3,\"D2\":150}"_json;
nlohmann::ordered_json ordered_j(original_j);
std::string s = ordered_j.dump();

内容的提问来源于stack exchange,提问作者user20420531

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 23:33:21