2

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.

1
  • Where is that additional information coming from? What format is it in? Commented Mar 23, 2017 at 14:30

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

hi, how do you output the result as a json file?
@Hachi you can use this code stackoverflow.com/questions/12309269/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.