I am looking to convert a dataframe to json, this is the code I currently have:
my_frame = pd.DataFrame(
{'Age':[30, 31],
'Eye':['blue', 'brown'],
'Gender': ['male', 'female']})
my_frame = my_frame.to_json(orient='records')
my_frame
Result:
'[{"Age":30,"Eye":"blue","Gender":"male"},{"Age":31,"Eye":"brown","Gender":"female"}]'
I want to add keys to the json object and add the key info over the entire data that was converted from the dataframe.
add_keys = {'id': 101,
'loc': 'NY',
}
add_keys['info'] = my_frame
add_keys
Result:
{'id': 101,
'info': '[{"Age":30,"Eye":"blue","Gender":"male"},
{"Age":31,"Eye":"brown","Gender":"female"}]',
'loc': 'NY'}
I want to print each of the two records within info, however when I run this iterative code it outputs each character of the string rather than the entire record. I believe this may be an issue from how I am adding the keys.
for item in add_keys['info']:
print(item)
Any help greatly appreciated!
add_keys['info'], not the JSON representation.my_frameis a string, you need to convert it, something like this:add_keys['info'] = json.loads(my_frame)