使用Python 3.8脚本更改json值 TypeError:“ str”对象不支持项目分配脚本:item['hotKey'] = "<f11>"

问题描述

我想用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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...