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

基于nlohmann json库构建指定格式JSON机场数组的技术问题

解决nlohmann JSON生成目标数组结构的问题

我来帮你搞定这个nlohmann JSON的问题!你现在的核心问题是把airports字段当成了JSON对象(键值对结构)来操作,所以生成了以机场代码为key的嵌套对象,而非你需要的数组结构。另外你提到生成数组时会覆盖最后一条数据,大概率是因为每次添加新机场时都重新初始化了数组,而不是往已有数组里追加元素。

正确实现代码

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

// 初始化主JSON对象
json airports;

// 确保"airports"字段是数组(仅在第一次使用时初始化)
if (!airports.contains("airports") || !airports["airports"].is_array()) {
    airports["airports"] = json::array();
}

// 添加第一个机场LGW
std::string inputShortVersion = "LGW";
std::string inputCity = "London";
std::string inputAddress = "Horley, Gatwick RH6 0NP, UK";

// 创建单个机场的JSON对象
json airport_entry;
airport_entry["shortVersion"] = inputShortVersion;
airport_entry["city"] = inputCity;
airport_entry["address"] = inputAddress;

// 将机场对象追加到数组中
airports["airports"].push_back(airport_entry);

// 添加第二个机场RIX
inputShortVersion = "RIX";
inputCity = "Riga";
inputAddress = "Marupe, LV-1053";

json another_airport;
another_airport["shortVersion"] = inputShortVersion;
another_airport["city"] = inputCity;
another_airport["address"] = inputAddress;

airports["airports"].push_back(another_airport);

// 输出验证结果
std::cout << airports.dump(4) << std::endl;

问题根源说明

  1. 原代码的结构错误:你之前的写法airports["airports"][inputShortVersion]是在给airports对象添加键值对,每个机场代码对应一个子对象,自然生成的是对象而非数组。
  2. 数组覆盖的原因:如果你之前尝试生成数组时,每次添加新机场都重新执行airports["airports"] = json::array();,这会清空之前的数组内容,最终只会保留最后一条数据。所以要确保数组只初始化一次,之后用push_back追加新元素。

运行上述代码后,你就能得到完全符合要求的JSON结构:

{
    "airports": [
        {
            "address": "Horley, Gatwick RH6 0NP, UK",
            "city": "London",
            "shortVersion": "LGW"
        },
        {
            "address": "Marupe, LV-1053",
            "city": "Riga",
            "shortVersion": "RIX"
        }
    ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:04:28