I have json data about flight reservations coming from a MongoDB. This data is inseted into a PostgreSQL table and the data type is json. The itinerary information has the following structure.
[
{
"segments": {
"1": {
"airline": "G8",
"flight_number": "761",
"arrival-date": "2018-11-02T12:45:00",
"arrival_airport": "CCU",
"departure_date": "2018-11-02T11:35:00",
"departure_airport": "BBI",
"operating_airline": "G8",
"stops": 0,
"index": 1,
"duration": 4200
}
}
},
{
"segments": {
"2": {
"airline": "6E",
"flight_number": "775",
"arrival-date": "2018-11-03T00:30:00",
"arrival_airport": "BBI",
"departure_date": "2018-11-02T23:20:00",
"departure_airport": "CCU",
"operating_airline": "6E",
"stops": 0,
"index": 2,
"duration": 4200
}
}
}
]
The number of segments is unknown. How can this be split into multiple records so that each segment becomes a record?
json_array_elements is a function I am already using and if I use json_array_elements(data->'flights')->'segments', I get output like this
{
"1": {
"airline": "AI",
"flight_number": "20",
"arrival_airport": "CCU",
"arrival-date": "2018-10-17T16:40:00",
"departure_date": "2018-10-17T14:25:00",
"departure_airport": "DEL",
"operating_airline": "AI",
"stops": 0,
"index": 1,
"duration": 8100
},
"2": {
"airline": "AI",
"flight_number": "230",
"arrival_airport": "DAC",
"arrival-date": "2018-10-17T20:25:00",
"departure_date": "2018-10-17T19:00:00",
"departure_airport": "CCU",
"operating_airline": "AI",
"stops": 0,
"index": 2,
"duration": 3300
}
}
How can this be converted into individual records? I would like to execute an insert like this -
insert into stage_itinerary (segment_id,airline,flight_number,arrival_aiport...) select (....)