使用用户输入创建 json 数据库

Creating a json database with user input

我需要创建我的 .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 库。

您在所需的输出中有一个 sequence 容器,但在您的代码中有一个 associative 容器。

试试

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

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

显然,您正在创建 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}
    });