问题描述
我想用Python 3.8脚本更改一个json值。
我知道在Python中,字符串是不可变的,因此您不能就地更改其字符。
这对我有很大帮助:How to find and replace a part of a value in json file
TypeError:“ str”对象不支持项目分配
TypeError: 'str' object does not support item assignment
item ['hotKey'] =“” TypeError:“ str”对象不支持项目分配
脚本:item['hotKey'] = "<f11>"
from pathlib import Path
import json
home = str(Path.home())
path = home + "/.config/autokey/data/Sample Scripts/"
jsonFilePath = home + "/.config/autokey/data/Sample Scripts/.run-run-lintalistAHK-all.json"
with open(jsonFilePath) as f:
data = json.load(f)
for item in data['hotkey']:
item['hotKey'] = "<f11>" # item['hotKey'].replace('$home',item['id'])
with open(jsonFilePath,'w') as f:
json.dump(data,f)
json文件
{
"hotkey": {
"hotKey": "<f12>"
},}
解决方法
您需要在之前添加json['hotkey']
参考:
for item in data['hotkey']:
data['hotkey'][item] = "<f11>" # item['hotKey'].replace('$home',item['id'])
我的原始尝试:
import json
j = '''
{
"hotkey": {
"hotKey": "<f12>"
}
}
'''
data = json.loads(j)
for x in data['hotkey']:
data['hotkey'][x] = '<f11>'
print(data)