简体   繁体   中英

I am getting a KeyError when flattening my JSON file. How do I solve this?

I have the following list of dictionaries loaded from a JSON file:

data = [
  {
    'sales_id': 788,
    'company_name': 'Montreal_1',
    'order_details': [
      {
        'order_id': 988,
        'order_name': 'My Playstore',
        'external_label': None,
        'order_start_date': '2023-01-16T10:00:00-04:00',
        'order_end_date': '2029-01-17T23:59:59-04:00', 
        'associated_orders': [
          {
            'associated_order_id': 129,
            'associated_order_name': 'Yellow'
          }
        ]
      }
    ]
  }
]

I want to flatten the list, up to the associated_order_id / associated_order_name level. This means I want to include all the data in the JSON template up to the associated_orders level.

Here is my intended output (the columns I need):

sales id |  company_name | order_id | order_name | external label | order_start_date | order_end_date | associated_order_id | associated_order_name 

Here is what I use:

json_normalize(data, record_path = 'associated_orders', meta = ['sales_id','company_name',[['order_details','associated_orders']])

I get a KeyError

Can anyone help me please?

You will need to put the complete path in record_path

json_normalize(data, 
record_path=['order_details','associated_orders'], 
meta=['sales_id','company_name',
['order_details','order_id'],
['order_details','order_name'],
['order_details','external_label'],
['order_details','order_start_date'],
['order_details','order_end_date'],
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM