Skip to content
Advertisement

Add a object one level higher in pandas json

I’m new to json and pandas and want to output my data in the following schema, but I’m not sure how to add the leading ‘results’.

My dataframe:

Name     Id    Qty   Value
thing1   123   10    12.5
thing2   456   20    15.4
thing3   789   40    84.2

My code:

json_output = df.reset_index().to_json(orient='record')

My Json output:

[{"id":456,
  "name":"thing2",
  "qty":20,
  "value":15.4
 },
 "id":123,
  "name":"thing1",
  "qty":10,
  "value":12.4
 },
  "id":789,
  "name":"thing3",
  "qty":40
  "value":84.2
 }
]

My Json schema that I want:

results:

     id:

     name:

     qty:

     value:

Advertisement

Answer

Try this:

import pandas as pd
import json

tmp = [('thing1', 123, 10, 12.5),
            ('thing2', 456, 20, 15.4),
            ('thing3', 789, 40, 84.2),
            ]

df = pd.DataFrame(tmp, columns=['Name', 'Id','Qty', 'Value'], )
df_dict = df.to_dict(orient='records')
final_dict = {'results': df_dict}
json_output = json.dumps(final_dict)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement