我想用 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>"
},
}