Ariel Ariel -4 years ago 244
JSON Question

Python dataframe to JSON add additional fields

I am looking to transform my dataframe to json

Age Eye Gender
30 blue male


My current code, I convert the dataframe to json and get the below result:

json_file = df.to_json(orient='records')

json_file

[{'age':'30'},{'eye':'blue'},{'gender':'male'}]


However, I want to add an additional layer that would state the id and name to the json data and then label it as 'info'.

{'id':'5231'
'name':'Bob'
'info': [
{'age':'30'},{'eye':'blue'},{'gender':'male'}
]
}


How would I add the additional fields? I tried reading the docs however I do not see a clear answer on how to add the additional fields in during dataframe to json conversion.

Answer Source

Based on the data you provided this is your answer:

import pandas as pd

a = {'id':'5231',
    'name':'Bob',
}

df = pd.DataFrame({'Age':[30], 'Eye':['blue'], 'Gender': ['male']})
json = df.to_json(orient='records')

a['info'] = json
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download