0

我需要创建我的 .json 数组,如下所示:

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

但我现在看起来像这样:

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

我现在用于用户输入的代码是这样的:

airports["airports"][inputShortVersion]["shortVersion"] = inputShortVersion;
airports["airports"][inputShortVersion]["city"] = inputCity;
airports["airports"][inputShortVersion]["address"] = inputAddress;

我已经搜索了一整天关于如何做到这一点,但我最接近的是它确实创建了上述数组但在输入后它会覆盖最后一个机场数据。

我正在使用 nlohmann json 库。

4

2 回答 2

1

您在所需的输出中有一个序列容器,但在您的代码中有关联容器。

尝试类似的东西

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

airports["airports"].push_back(inputAirport);
于 2019-02-27T11:32:42.340 回答
1

显然,您正在创建一个 json 对象而不是 json 数组。要获取数组,您可以尝试按照以下方式进行操作:

airports["airports"] = nlohmann::json::array()

new_airport = nlohmann::json::object()
new_airport["shortVersion"] = inputShortVersion;
new_airport["city"] = inputCity;
new_airport["address"] = inputAddress;

airports["airports"].emplace_back(new_airport);

这可以用花括号初始化器列表写得更短,但以牺牲可读性为代价:

airports["airports"] = nlohmann::json::array()

airports["airports"].emplace_back(
    {
        {"shortVersion", inputShortVersion},
        {"city", inputCity},
        {"address", inputAddress}
    });
于 2019-02-27T11:35:48.113 回答