简体   繁体   中英

Python: How to append a JSON object to a JSON array

I would like to append a JSON object that contains example informations to "list" JSON array from my python file to my JSON file

My python file:

import json

with open("mydata.json", "r+") as f:
    data = json.load(f)
    data["list"].append(
        {"a": "1"}
    )

    json.dump(data, f, indent=4)

My JSON file:

{
    "list": [

    ]
}

I was expecting this result from my JSON file:

{
    "list": [
        {
            "a": "1"
        }
    ]
}

But I got this instead:

{
    "list": [

    ]
}{
    "list": [
        {
            "a": "1"
        }
    ]
}

Do you guys have any idea why this happended and how to fix it?

You dumped the updated JSON at the end of the original file, rather than replacing it. You should reopen the file to overwrite it.

import json

with open("mydata.json", "r") as f:
    data = json.load(f)
data["list"].append(
    {"a": "1"}
)
with open("mydata.json", "w") as f:
    json.dump(data, f, indent=4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM