簡體   English   中英

如何使用 python 中的分組鍵將 OrderedDict 列表轉換為嵌套 json

[英]How to convert a list of OrderedDict to nested json with grouped keys in python

我正在做一個項目,我需要將數據庫中的一組數據行轉換list of OrderedDict用於其他目的,並使用此list of OrderedDict轉換為 python 中的nested JSON python 我開始學習 python。 我能夠將來自數據庫的查詢響應( list of lists轉換list of OrderedDict

list of OrderedDict如下:

    {
'OUTBOUND': [
OrderedDict([('Leg', 1), ('SessionID', 'W12231fwfegwcaa2'),('FeeCode', 'ATO'),('SeatGroup', '2'),
               ('Currency', 'MXN'),('Modality', 'VB'),('BookingClass', 'A'),('Price', 145.0),('Num_Pax', 1),('Channel', 'Web')]),
  OrderedDict([('Leg', 1),('SessionID', 'W12231fwfegwcaa2'),('FeeCode', 'ATO'),('SeatGroup', '4'),
               ('Currency', 'MXN'),('Modality', 'VB'),('BookingClass', 'A'),('Price', 111.0),('Num_Pax', 1),('Channel', 'Web')]),
  OrderedDict([('Leg', 1),('SessionID', 'W12231fwfegwcaa2'),('FeeCode', 'BDM'),('SeatGroup', 'null'),
               ('Currency', 'MXN'),('Modality', 'VB'),('BookingClass', 'A'),('Price', 111.0),('Num_Pax', 1),('Channel', 'Web')]),
  OrderedDict([('Leg', 2),('SessionID', 'W12231fwfegwcaa2'),('FeeCode', 'ATO'),('SeatGroup', '1'),
                ('Currency', 'MXN'),('Modality', 'VB'),('BookingClass', 'U'),('Price', 180.0),('Num_Pax', 1),('Channel', 'Web'))]),
  OrderedDict([('Leg', 2),('SessionID', 'W12231fwfegwcaa2'),('FeeCode', 'ATO'),('SeatGroup', '4'),
                ('Currency', 'MXN'),('Modality', 'VB'),('BookingClass', 'U'),('Price', 97.0),('Num_Pax', 1),('Channel', 'Web')]),
  OrderedDict([('Leg', 2),('SessionID', 'W12231fwfegwcaa2'),('FeeCode', 'BDM'),('SeatGroup', 'null'),
                ('Currency', 'MXN'),('Modality', 'VB'),('BookingClass', 'U'),('Price', 97.0),('Num_Pax', 1),('Channel', 'Web')])
            ]
}

我需要如下嵌套格式:

{
"OUTBOUND": [
    {
      "Leg": 1,
      "SessionID": "W12231fwfegwcaa2",
      "Modality": "VB",
      "BookingClass": "A",
      "FeeCodes":[
                    {
                        "FeeCode": "ATO",
                        "Prices":
                        [
                            {
                                "SeatGroup": "2",
                                "Price": 145.0,
                                "Currency": "MXN"
                            },
                            {
                                "SeatGroup": "4",
                                "Price": 111.0,
                                "Currency": "MXN"
                            }
                        ]
                    },
                    {
                        "FeeCode": "VBABDM",                
                        "Prices":
                        [ 
                            {
                                "SeatGroup": "null",
                                "Price": 111.0,
                                "Currency": "MXN"                   
                            }
                        ]
                    }
                ],
      "Num_Pax": 1,
      "Channel": "Web"
    },
    {
      "Leg": 2,
      "SessionID": "W12231fwfegwcaa2",
      "Modality": "VB",
      "BookingClass": "U",
      "FeeCodes":[
                    {
                        "FeeCode": "ATO",
                        "Prices":
                        [
                            {
                                "SeatGroup": "1",
                                "Price": 180.0,
                                "Currency": "MXN"
                            },
                            {
                                "SeatGroup": "4",
                                "price": 97.0,
                                "Currency": "MXN"
                            }
                        ]
                    },
                    {
                        "FeeCode": "VBABDM",                
                        "Prices":
                        [ 
                            {
                                "SeatGroup": "null",
                                "price": 97.0,
                                "Currency": "MXN"                   
                            }
                        ]
                    }
                ],
      "Num_Pax": 1,
      "Channel": "Web"
    }
    ]
}

如果我沒記錯的話,我需要按LegSessionIDModalityBookingClassNumPaxChannel分組,並將FeeCodeSeatGroupPriceCurrency分組為嵌套格式,但無法繼續討論如何循環和分組嵌套。

如果我能得到一些幫助,那就太好了。 謝謝

我能夠編寫一個 python 代碼來獲得所需的格式,使用簡單的循環並在 output 中進行一些更改,例如字段 SessionID、Num_Pax 和 Channel 被取出然后生成 OUTBOUND 字段和其中的字段。

我沒有使用 OrderedDict,而是使用列表列表作為輸入,將其轉換為 Pandas DataFrame 並使用 DataFrame 來獲得嵌套格式。

下面是我使用的代碼:

outbound_df = pd.DataFrame(response_outbound,columns=All_columns)
Common_columns = ['Leg', 'Modality', 'BookingClass']

### Taking SessionID, AirlineCode,Num_Pax and Channel outside OUTBOUND part as they are common for all the leg level data
response_data['SessionID'] = outbound_df['SessionID'].unique()[0]   
response_data['Num_Pax'] = int(outbound_df['Num_Pax'].unique()[0])
response_data['Channel'] = outbound_df['Channel'].unique()[0]

temp_data = []
Legs = outbound_df['Leg'].unique()

for i in Legs:
    subdata = outbound_df[outbound_df['Leg']==i]
    
    ### Initializing leg_data dict
    leg_data = collections.OrderedDict()
        
    ### Populating common fields of the leg (Leg, Modality,BookingClass)
    for j in Common_columns: 
        if(j=='Leg'):
            leg_data[j] = int(subdata[j].unique()[0])
        else:
            leg_data[j] = subdata[j].unique()[0]
    
    leg_data['FeeCodes'] = []
    FeeCodes = subdata['FeeCode'].unique()
    
    for fc in FeeCodes:
        subdata_fees = subdata[subdata['FeeCode']==fc]
        
        Prices = {'FeeCode':fc, "Prices":[]}
        
        for _,rows in subdata_fees.iterrows():
            data = {}
            data['SeatGroup'] = rows['SeatGroup']
            data['Price'] = float(rows['Price'])
            data['Currency'] = rows['Currency']
            
            Prices["Prices"].append(data)
        
        leg_data["FeeCodes"].append(Prices)
    temp_data.append(leg_data)

response_data["OUTBOUND"] = temp_data

我可以在response_data上執行json.dumps以獲得 json 格式,該格式將發送到下一步。

下面是我得到的 output 格式:

{
   "SessionID":"W12231fwfegwcaa2",
   "Num_Pax":1,
   "Channel":"Web",
   "OUTBOUND":[
      {
         "Leg":1,
         "Modality":"VB",
         "BookingClass":"A",
         "FeeCodes":[
            {
               "FeeCode":"ATO",
               "Prices":[
                  {
                     "SeatGroup":"2",
                     "Price":145.0,
                     "Currency":"MXN"
                  },
                  {
                     "SeatGroup":"4",
                     "Price":111.0,
                     "Currency":"MXN"
                  }
               ]
            },
            {
               "FeeCode":"VBABDM",
               "Prices":[
                  {
                     "SeatGroup":"null",
                     "Price":111.0,
                     "Currency":"MXN"
                  }
               ]
            }
         ]
      },
      {
         "Leg":2,
         "Modality":"VB",
         "BookingClass":"U",
         "FeeCodes":[
            {
               "FeeCode":"ATO",
               "Prices":[
                  {
                     "SeatGroup":"1",
                     "Price":180.0,
                     "Currency":"MXN"
                  },
                  {
                     "SeatGroup":"4",
                     "price":97.0,
                     "Currency":"MXN"
                  }
               ]
            },
            {
               "FeeCode":"VBABDM",
               "Prices":[
                  {
                     "SeatGroup":"null",
                     "price":97.0,
                     "Currency":"MXN"
                  }
               ]
            }
         ]
      }
   ]
}

請讓我知道我們是否可以在冗長的迭代或任何其他更改方面縮短代碼。 謝謝。 PS:抱歉我的編輯錯誤

假設您將字典存儲到某個變量foo ,您可以執行以下操作:

import json

json.dumps(foo)

請注意,您在第 4 個元素OUTBOUND列表中添加了額外的括號

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM