Search code examples
pythonarraysjsonpandasto-json

Use to_json but with overall data name


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"
        }
    ]
}

Solution

  • 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)