Python 如何更改json文件中嵌套键的值?
我想更改嵌套键的值,但出现此错误Python 如何更改json文件中嵌套键的值?,python,json,kivy,Python,Json,Kivy,我想更改嵌套键的值,但出现此错误 key['score'] = new_score # come back to this TypeError: 'str' object does not support item assignment 这是我的密码: def add_score(self, obj): for child in reversed(self.root.screen_two.ids.streak_zone.children): name
key['score'] = new_score # come back to this
TypeError: 'str' object does not support item assignment
这是我的密码:
def add_score(self, obj):
for child in reversed(self.root.screen_two.ids.streak_zone.children):
name = child.text
with open("streak.json", "r+") as read_file:
data = json.load(read_file)
for key in data.keys():
if key == name:
score = data.get(key, {}).get('score')
new_score = score + 1
key['score'] = new_score # come back to this
这就是我的json文件的样子:
{"one": {"action": "one",
"delay": 1557963534.4314187,
"seconds": 60,
"score": 0,
"delta": 1557963474.4314187},
"two": {"action": "two",
"delay": 1557963664.037102,
"seconds": 120,
"score": 0,
"delta": 1557963544.037102},
"three":{"action": "three",
"delay": 1557963792.4683638,
"seconds": 180,
"score": 0,
"delta": 1557963612.4683638}
}
如何更改json文件中的
分数值?您应该能够直接更新dictionary元素
替换以下内容:
for key in data.keys():
if key == name:
score = data.get(key, {}).get('score')
new_score = score + 1
key['score'] = new_score # come back to this
与
所以代码应该是
def add_score(self, obj):
for child in reversed(self.root.screen_two.ids.streak_zone.children):
name = child.text
with open("streak.json", "r+") as read_file:
data = json.load(read_file)
data[name]['score'] += 1
在for循环中,您正在迭代keys数组,在您的例子中,它是['one','two','three']
试试下面的代码。希望这会有帮助
for key,value in data.items():
if key == name:
score = value['score']
new_score = score + 1
value['score'] = new_score
或用于一个衬里,而不是用于下面的回路
data[name]['score']+=1#name='one'
在文件中编辑
以open('streak.json','r+')作为f的:
data=json.load(f)
数据[名称]['score']+=1
f、 搜索(0)
dump(数据,f,缩进=4)
f、 截断()
这应该行得通
with open("a.json", "r+") as read_file:
data = json.load(read_file)
data[name]['score'] += 1 # update score
with open("a.json", "w") as json_file: #write it back to the file
json.dump(data, json_file)
我需要保留代码的if key==name:
protion,因为程序不知道key
是什么,当我生成代码时:key[name]['score']+=1
I getTypeError:字符串索引必须是整数
刚刚确认您用我建议的修复替换了5行吗?当我这样做时,我得到的是`NameError:name'key'未定义`对不起,我的结尾有错。我已经更新了答案以使用data not KeyJSON文件中的score
值仍然没有更改。我的json文件中的score
值没有更改。@yemi.JUMP这是因为您正在读取/解析json文件并将数据存储到一个变量中,然后对该文件中没有的变量执行操作。抱歉如果我不清楚我的问题。我已经编辑了我的文章,其中包括我希望文件更改的内容。您提供的原始问题和代码没有提到写入文件。@bkyada尽管此方法有效,但每个名为score的值都会更改。有没有办法只更改一个score
change?我的json文件中score的值不会更改。为此,您必须将“数据”写回该文件。使用json.dump()
with open("a.json", "r+") as read_file:
data = json.load(read_file)
data[name]['score'] += 1 # update score
with open("a.json", "w") as json_file: #write it back to the file
json.dump(data, json_file)