Python3.7JSON-AttributeError';dict没有属性“;改为';

Python3.7JSON-AttributeError';dict没有属性“;改为';,python,json,python-3.x,attributeerror,Python,Json,Python 3.x,Attributeerror,我正在用JSON做一些简单的练习,突然,我发现一些错误阻止了字典转换为JSON并记录在文件中: import json i = { "element" : "some element", "items" : [ 1, "true", "thing" ], "nested": { "dfadf": "1", "adfgf": "2" } } file = json.load(i) 导入json i={ “元

我正在用JSON做一些简单的练习,突然,我发现一些错误阻止了字典转换为JSON并记录在文件中:

import json i = { "element" : "some element", "items" : [ 1, "true", "thing" ], "nested": { "dfadf": "1", "adfgf": "2" } } file = json.load(i) 导入json i={ “元素”:“某些元素”, “项目”:[ 1、“真实”、“真实” ], “嵌套”:{ “dfadf”:“1”, “adfgf”:“2” } } file=json.load(i) 返回:

Traceback (most recent call last): File "context-manager.py", line 15, in file = json.load(i) File (...)"\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 293, in load return loads(fp.read(), AttributeError: 'dict' object has no attribute 'read' PS (...)\json> 回溯(最近一次呼叫最后一次): 文件“context manager.py”,第15行,在 file=json.load(i) 文件(…)“\AppData\Local\Programs\Python\Python37-32\lib\json\\ uuu init\uuu.py”,第293行,处于加载状态 返回加载(fp.read(), AttributeError:“dict”对象没有属性“read” PS(…)\json> 我尝试粘贴基本功能代码,但在尝试转储到文件时出现了相同的错误,或者“写入”错误。我的Python安装是否可能已损坏?(我使用公司的笔记本,但直到昨天一切都正常) 安装程序:Windows10,Python3.7.4(使用命令'py'运行以不启动Python2.7)


非常感谢您的意见!

您必须打开该文件并使用
json.dump
将json写入该文件

with open("filename.json", 'w+') as file:
  json.dump(file, i)
如果文件不存在,参数
w+
将创建该文件

如果只想将其转换为字符串而不写入文件,请使用
json.dumps

json_content = json.dumps(i)

i
不是JSON,它是一个字典。使用
JSON.dumps()
转储到字符串。非常感谢您的回答。问题出在open()的“w+”参数中。我保留“r”以保存和使用内容,直到最后编写,但忘记了它并开始随机代码。