Home > Software design >  convert json data to pandas dataframe in python (dictionary inside list )
convert json data to pandas dataframe in python (dictionary inside list )

Time:09-21

I have json data like below:

{"name": "Monkey", "image": "https://media.npr.org/assets/img/2017/09/12/macaca_nigra_self-portrait-3e0070aa19a7fe36e802253048411a38f14a79f8-s800-c85.webp", "attributes": [{"trait_type": "Bones", "value": "Zombie"}, {"trait_type": "Clothes", "value": "Striped"}, {"trait_type": "Mouth", "value": "Bubblegum"}, {"trait_type": "Eyes", "value": "Black Sunglasses"}, {"trait_type": "Hat", "value": "Sushi"}, {"trait_type": "Background", "value": "Purple"}]}

I want to convert this json data as pandas dataframe only selecting the attributes as filter it as below:

Bones   Clothes    Mouth      Eyes    Hat      Background
zombie   striped    bubblegum  black   sushi    purple

Can any expert please help me to get the output as i mentioned Thank you

CodePudding user response:

There is probably a prettier solution but this does the job:

import json 
import pandas as pd

with open('file.json') as f:
    trait_types= []
    values = []
    data = json.load(f)
    df = pd.DataFrame(data)
    for key in data['attributes']:
        trait_types.append(key['trait_type'])
        values.append(key['value'])
df = pd.DataFrame({
    'trait type': trait_types,
    'value' : values})
print(df)
  • Related