简体   繁体   中英

I cant append to my JSON array with Python

This doesn't seem to work with this line being the issue

data["Objects"]["Text"].append({"f":"var6", "g":"var7", "h":"var8"})

This is the entire function

def CreateTextJSON(TextObject):
    print("s")
    with open('base.json') as f:
        data = json.load(f)

    data["Objects"]["Text"].append({"f":"var6", "g":"var7", "h":"var8"})

    with open('base.json', 'w') as f:
        json.dump(data, f)

This is my JSON (base.json)

{
    "Objects": [
    {
        "Type": "Menu",
        "Path": "assets/images/mainmenu/mainmenu.png",
        "Name": "MainMenu",
        "X": 0,
        "Y": 0,
        "Width": 1920,
        "Height": 1080,
        "Buttons": [],
        "Text": []
    }]
}

Im trying to add to the [Text] array but I can't seem to.

Credit to @Grismar "Also, the problem would seem to be that "Objects" is not a dictionary, but a list with 1 element, which is the dictionary, so you need data["Objects"][0]["Text"].append(..."

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