基于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;
问题根源说明
- 原代码的结构错误:你之前的写法
airports["airports"][inputShortVersion]是在给airports对象添加键值对,每个机场代码对应一个子对象,自然生成的是对象而非数组。 - 数组覆盖的原因:如果你之前尝试生成数组时,每次添加新机场都重新执行
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
相关产品推荐
相关产品推荐

