1

我正在做一个项目,我需要将一组数据行从数据库转换list of OrderedDict为其他目的,并使用它list of OrderedDict转换nested JSONpython. 我开始学习python。我能够将来自数据库的查询响应转换list of listslist 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"
    }
    ]
}

如果我没记错的话,我需要按LegSessionIDModality、和分组BookingClass,并将、和分组为上面的嵌套格式,但无法继续讨论如何循环和分组嵌套。NumPaxChannelFeeCodeSeatGroupPriceCurrency

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

4

2 回答 2

0

我能够编写一个 python 代码来获取我需要的格式,使用简单的循环在输出中进行一些更改,例如将 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

我可以json.dumps继续response_data获取将发送到下一步的 json 格式。

以下是我得到的输出格式:

{
   "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:抱歉我的编辑错误

于 2021-03-05T08:14:46.520 回答
-1

假设您将字典存储到某个变量foo中,您可以执行以下操作:

import json

json.dumps(foo)

OUTBOUND请注意,您在第 4 个元素列表中添加了额外的括号

于 2021-02-26T12:03:33.737 回答