首页 > 解决方案 > Python:更改 JSON 中的元素

问题描述

我正在尝试遍历 JSON“卡片”列表并更新 ID 为 1 的卡片的描述。看起来很简单,我不确定我哪里出错了。代码:

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

我在哪里错了?就好像这条线aCard["sections"][0]["payload"][0]["description"] = newData被完全忽略了,或者我做错了什么。

谢谢!

标签: pythonjsonfor-loopelement

解决方案


不,它没有被忽略,但您没有打印单元格的新内容。考虑以下代码:

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

你期望看到什么?我期待看到的是“速成棕狐”。当我更改 的值时,它对绑定a的字符串没有任何作用。b

这正是您在上面看到的。 description不指向那个单元格。它指的是在单元格中开始的字符串。当您更改单元格的值时,它现在绑定到一个新字符串,但description仍绑定到旧字符串。

只是print(aCard["sections"][0]["payload"][0]["description"]),你会发现它很好。


推荐阅读