Home > Blockchain >  Changing format of json file
Changing format of json file

Time:09-30

I am writing a DataFrame to json like this which gives me the correct format of the output:

json_data = df.to_json(orient='records')
parser = json.loads(json_data)
json_data = json.dumps(parser, indent=4, ensure_ascii=False)

The output of this looks like this:

[
    {
        "att1": "321",
        "att2": "abc",
        "att3": "cba"
    },
    {
        "att1": "abc",
        "att2": "cba",
        "att3": "123"
    }
]

However, i would like to add a top layer and make it a json object. So the output i would like is this:

{
    "top":[
        {
            "att1": "321",
            "att2": "abc",
            "att3": "cba"
        },
        {
            "att1": "abc",
            "att2": "cba",
            "att3": "123"
        }
    ]
}

Is there a way to do this with the pandas to_json function, or do i have to do it manually? In any case, how can i edit my file to have the desired format? Any help is appreciated.

CodePudding user response:

Try this

json_data = df.to_json(orient='records')
parser = {}
parser["top"] = json.loads(json_data)
json_data = json.dumps(parser, indent=4, ensure_ascii=False)
  • Related