0

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

1 回答 1

2

您需要在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)
于 2020-11-07T13:26:41.047 回答