TypeError:'str'对象不支持项目分配,带有json文件的python - python

以下是我的代码

import json
with open('johns.json', 'r') as q:
    l = q.read()
    data = json.loads(l)
    data['john'] = '{}'
    data['john']['user'] = 'hey'

以下是json文件

{}

每次我运行代码时,都会收到错误消息

    data['john']['user'] = 'hey'
TypeError: 'str' object does not support item assignment

有没有办法解决这个问题,并使data ['john'] ['user']相等呢?

参考方案

您的代码中有一些错误。首先,可以使用json.load代替json.loads。前者用于直接从json文件获取数据。

然后,您要为data['john']指定一个字符串,而不是实际的字典。

import json
with open('johns.json', 'r') as q:
    data = json.load(q)
    data['john'] = {}
    data['john']['user'] = 'hey'

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

TypeError:promovePeao()缺少1个必需的位置参数:'player'[重复] - python

This question already has answers here: TypeError: Missing 1 required positional argument: 'self'                                                                    (5个答案…

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…