I'm trying to use to_json
to create a json file with python. I have it working so far to produce the following sort of output:
[
{
"Country": "A",
"Title": "B",
"Category": "C"
},
{
"Country": "D",
"Title": "E",
"Category": "F"
}
]
But I need it to create a json file that looks like this. Quite simply, to add the "data" name. Any tips on how to do so?
{
"data": [
{
"Country": "A",
"Title": "B",
"Category": "C"
},
{
"Country": "D",
"Title": "E",
"Category": "F"
}
]
}
CodePudding user response:
I don't think .to_json()
can do this by itself. Use df.to_dict('records')
to create the list of dictionaries, then put that list inside another dictionary and write that JSON to the file.
d = {"data": df.to_dict('records')}
with open("file.json", "w") as f:
json.dump(d, f)
CodePudding user response:
why don't you just create a dictionary and add your output (list) as a value which 'data' is its key and dump it to make a json format?!
CodePudding user response:
orient str
Indication of expected JSON string format.
‘records’ : list like [{column -> value}, … , {column -> value}]
df.to_json(....., orient='records')