使用 Python 3.8 脚本更改 json 值
change a json value with a Python 3.8 script
我想用 Python 3.8 脚本更改一个 json 值。
我知道 Python,字符串是不可变的,所以你不能就地改变它们的字符。
这对我很有帮助:
TypeError: 'str' 对象不支持项目分配
TypeError: 'str' object does not support item assignment
item['hotKey'] = ""
TypeError: 'str' object does not support item assignment
脚本: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)
我想用 Python 3.8 脚本更改一个 json 值。
我知道 Python,字符串是不可变的,所以你不能就地改变它们的字符。
这对我很有帮助:
TypeError: 'str' 对象不支持项目分配
TypeError: 'str' object does not support item assignment
item['hotKey'] = "" TypeError: 'str' object does not support item assignment
脚本: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)