简体   繁体   中英

complex json to csv using python and pandas dataframe

i know this problem has been asked many times but still i am not able to convert it to json.

my json file look like this:

{
    "itemCostPrices": {
        "Id": 1,
        "costPrices": [{
            "costPrice": 83.56,
            "currencyCode": "GBP",
            "startDateValid": "2010-09-06",
            "endDateValid": "2011-05-01",
            "postCalculatedCostPriceFlag": false,
            "promoCostPriceFlag": true
        }]
    },
    "eventId": null,
    "eventDateTime": null
}

Try this code:

import json
import pandas as pd

def flatten_dict(d, acc={}):
    for k, v in d.items():
        if isinstance(v, dict):
            flatten_dict(v, acc)
        elif isinstance(v, list):
            for l in v:
                flatten_dict(l, acc)
        else:
            acc[k] = v
    return acc


with open('tmp.json') as f:
    data = json.load(f)

df = pd.DataFrame([flatten_dict(d, {}) for d in data])
df.to_csv('tmp.csv', index=False)

Code explanation:

1) Read and import your json file into a dictionary:

with open('tmp.json') as f:
        data = json.load(f)

and you get:

[{'eventDateTime': None,
  'eventId': None,
  'itemCostPrices': {'Id': 1,
                     'costPrices': [{'costPrice': 83.56,
                                     'currencyCode': 'GBP',
                                     'endDateValid': '2011-05-01',
                                     'postCalculatedCostPriceFlag': False,
                                     'promoCostPriceFlag': True,
                                     'startDateValid': '2010-09-06'}]}},
 {'eventDateTime': None,
  'eventId': None,
  'itemCostPrices': {'Id': 2,
                     'costPrices': [{'costPrice': 99.56,
                                     'currencyCode': 'EUR',
                                     'endDateValid': '2017-05-01',
                                     'postCalculatedCostPriceFlag': False,
                                     'promoCostPriceFlag': True,
                                     'startDateValid': '2018-09-06'}]}}]

2) Flatten the dictionary:

flat_data = [flatten_dict(d, {}) for d in data]

and you get the following list of flatten dict:

[{'Id': 1,
  'costPrice': 83.56,
  'currencyCode': 'GBP',
  'startDateValid': '2010-09-06',
  'endDateValid': '2011-05-01',
  'postCalculatedCostPriceFlag': False,
  'promoCostPriceFlag': True,
  'eventId': None,
  'eventDateTime': None},
 {'Id': 2,
  'costPrice': 99.56,
  'currencyCode': 'EUR',
  'startDateValid': '2018-09-06',
  'endDateValid': '2017-05-01',
  'postCalculatedCostPriceFlag': False,
  'promoCostPriceFlag': True,
  'eventId': None,
  'eventDateTime': None}]

3) Load the dictionary in a pandas dataframe

df = pd.DataFrame(flat_data)

and you get:

   Id  costPrice currencyCode endDateValid eventDateTime eventId  postCalculatedCostPriceFlag  promoCostPriceFlag startDateValid
0   1      83.56          GBP   2011-05-01          None    None                        False                True     2010-09-06
1   2      99.56          EUR   2017-05-01          None    None                        False                True     2018-09-06  

4) Save your dataframe as csv

df.to_csv('tmp.csv', index=False)

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