Changing format of json file

pyth0nEiken

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.

Simeon

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)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related