Append JSON to existing object

Question:

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.

Asked By: pyth0nEiken

||

Answers:

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)
Answered By: Simeon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.