简体   繁体   中英

Python: Changing an Element in JSON

I'm trying to iterate over a list of JSON "Cards" and update the description of the one with id 1. Seems pretty simple and i'm not sure where i'm going wrong. Code:

data = json.load(f)
newData = "This is the correct data"
for aCard in data['theList']:
    if aCard["id"] == 1:
        print("Found id1") #works
        description = aCard["sections"][0]["payload"][0]["description"]
        print(description) #works
        aCard["sections"][0]["payload"][0]["description"] = newData
        print(description) #prints the same wrong data

Where am I going wrong here? It's as if this line aCard["sections"][0]["payload"][0]["description"] = newData is being completely ignored or i'm doing something incorrectly.

Thanks!

No, it's not being ignored, but you're not printing the new contents of the cell. Consider the following code:

a = "quick brown fox"
b = a
a = "lazy dog's back"
print(b)

What do you expect to see? What I expect to see is "quick brown fox". When I changed the value of a , that didn't do anything to the string that b is bound to.

That's exactly what you're seeing above. description doesn't POINT to that cell. It refers to the string that started out in the cell. When you change the value of the cell, it is now bound to a new string, but description is still bound to the old string.

Just print(aCard["sections"][0]["payload"][0]["description"]) and you'll see it's fine.

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