0

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"
        }
    ]
}
kodikai
  • 374
  • 1
  • 10

3 Answers3

2

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)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • This works, thanks @Barmar. I've marked this answer as correct but if you know of a way with .to_json too, that would be cool. – kodikai Nov 05 '22 at 11:36
0

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?!

  • 1
    This is really a comment, not an answer. With a bit more rep, [you will be able to post comments](//stackoverflow.com/privileges/comment). – Barmar Nov 05 '22 at 04:31
  • i know... but i need more reputation to write comment! but it is not far from the an answer @Barmar – Rahman Tavakoli Nov 05 '22 at 04:34
  • 1
    Obviously I know that, I wrote it in my comment. A good answer should show how to do it, not just describe it in vague terms. – Barmar Nov 05 '22 at 04:37
  • i know you knew it! it is an answer yeah it cant be compared with yours! obviously you have more experience in answering questions. thanks for your guidance @Barmar – Rahman Tavakoli Nov 05 '22 at 06:25
-1

orient str
Indication of expected JSON string format.
‘records’ : list like [{column -> value}, … , {column -> value}]

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html?highlight=to_json#pandas.DataFrame.to_json

df.to_json(....., orient='records')
Raibek
  • 558
  • 3
  • 6