0

I need to create my .json array to look like this:

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

But I have it looking right now like this:

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

The code I have for user input right now is this:

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

I've searched for a whole day on how to do this, but closest I got to was where it does create the above array but after input it overwrites the last airport data.

I'm using nlohmann json library.

Supreez
  • 3
  • 1

2 Answers2

1

You have a sequence container in your desired output, but associative container in your code.

Try something like

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

airports["airports"].push_back(inputAirport);
Caleth
  • 52,200
  • 2
  • 44
  • 75
1

Apparently, you are creating a json object instead of a json array. To get an array, you could try along the lines of the following:

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);

This can be written shorter with braced initalizer lists at the cost of readability:

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

airports["airports"].emplace_back(
    {
        {"shortVersion", inputShortVersion},
        {"city", inputCity},
        {"address", inputAddress}
    });
dasmy
  • 569
  • 4
  • 10