Home > Net >  complex json file to csv in python
complex json file to csv in python

Time:07-18

I need to convert a complex json file to csv using python, I tried a lot of codes without success, I came here for help,

csv file

{
    "_id": {
        "$oid": "2e3230s314i5dc07e118c8bo"
    },
    "add": {
        "address1": {
            "address_type": "Door",
            "address": "kvartira 14",
            "city": "new york",
            "region": null,
            "zipcode": "10005",
        },
        "name": "Evgeniya Kovantceva",
        "type": "Private person",
        "code": null,
        "additional_phone_nums": null,
        "email": null,
        "notifications": [],
        "address2": {
            "address": "kvartira 14",
            "city": "new york",
            "region": null,
            "zipcode": "10005",
            "country": "US",
            "country_name": "NY",
        }
    }
}

CodePudding user response:

import pandas as pd

null = 'null'

data = {
    "_id": {
        "$oid": "2e3230s314i5dc07e118c8bo"
    },
    "add": {
        "address": {
            "address_type": "Door",
            "address": "kvartira 14",
            "city": "new york",
            "region": null,
            "zipcode": "10005",
        },
        "name": "Evgeniya Kovantceva",
        "type": "Private person",
        "code": null,
        "additional_phone_nums": null,
        "email": null,
        "notifications": [],
        "address": {
            "address": "kvartira 14",
            "city": "new york",
            "region": null,
            "zipcode": "10005",
            "country": "US",
            "country_name": "NY",
        }
    }
}

df = pd.json_normalize(data)
df.to_csv('yourpath.csv')

Not very complex json I should say. I've seen a lot worse with nested lists of dictionaries etc.. Beware the null value. The "address" nested dictionary comes inside "add" two times almost identical?

  • Related