如何在python中将OrderedDict列表转换为带有分组键的嵌套json

如何在python中将OrderedDict列表转换为带有分组键的嵌套json,python,json,list,ordereddict,Python,Json,List,Ordereddict,我正在从事一个项目,其中需要将数据库中的一组数据行转换为OrderedICT列表以用于其他目的,并使用此OrderedICT列表转换为python中的嵌套JSON格式。我开始学习python了。我能够将数据库中的查询响应(列表列表)转换为OrderedICT列表 我已订购的信息通信技术清单如下: { 'OUTBOUND': [ OrderedDict([('Leg', 1), ('SessionID', 'W12231fwfegwcaa2'),('FeeCode', 'ATO'),('S

我正在从事一个项目,其中需要将数据库中的一组数据行转换为OrderedICT列表以用于其他目的,并使用此OrderedICT列表转换为python中的嵌套JSON格式。我开始学习python了。我能够将数据库中的查询响应(列表列表)转换为OrderedICT列表

我已订购的信息通信技术清单如下:

    {
'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"
    }
    ]
}
如果我没有错的话,我需要按Leg、SessionID、modity、BookingClass、NumPax和Channel分组,并将FeeCode、SeatGroup、Price和Currency分组为上述嵌套格式,但无法继续进行如何循环和分组嵌套


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

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

导入json json.dumpsfoo
请注意,您在第4个元素出站列表中添加了额外的括号

我能够编写一个python代码,使用简单的循环获得所需的格式,并在输出中进行了一些更改,如SessionID、Num_Pax和Channel字段,然后生成出站字段和其中的字段

我没有使用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即可获得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:很抱歉我的编辑错误

你只是想用这种格式打印字典吗?我需要将字典组织成给定的嵌套json格式,并传递到下一步。我相信他正在寻找要传递到此处的缩进参数。我想我的缩进不正确,但我在线检查,json结构似乎没有错误。