Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flatterning JSON to Pandas Dataframe

I’m trying to flattern this json into a pandas dataframe, but it’s getting the better of me.

[{
    'contact': {
        'id': 101,
        'email': 'email1@address.com',
    },
    'marketingPreference': [{
        'marketingId': 1093,
        'isOptedIn': True,
        'dateModifed': '2022-05-10T14:29:24Z'
    }]
},
{
    'contact': {
        'id': 102,
        'email': 'email2@address.com',
    },
    'marketingPreference': [{
        'marketingId': 1093,
        'isOptedIn': True,
        'dateModifed': '2022-05-10T14:29:24Z'
    }]
}
]

I am looking for the columns to be: Id, Email, MarketingId, IsOptedIn, DateModifed.

Even though marketingPreference is an array, there is only ever one json object inside.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use pd.json_normalize

df = pd.json_normalize(data, record_path='marketingPreference', meta=[['contact', 'id'], ['contact', 'email']])
print(df)

   marketingId  isOptedIn           dateModifed contact.id       contact.email
0         1093       True  2022-05-10T14:29:24Z        101  email1@address.com
1         1093       True  2022-05-10T14:29:24Z        102  email2@address.com
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading