TypeError:“str”对象不支持项分配,python带有json文件

2024-04-29 23:09:09 发布

您现在位置: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

有没有办法解决这个问题并使数据['john']['user']相等


Tags: 文件代码importjsonreaddataas错误
3条回答

您不应该在{}周围加引号,这样会创建字符串而不是字典

您也可以填写同一作业中的内容:

data['john'] = {"user": "hey"}

您的代码中有一些错误。首先,您可以使用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'

它必须读出来

data['john'] = dict()
# or data['john'] = {}

否则,data["john"]是一个字符串,即{}

相关问题 更多 >