Python 3.7 JSON - 属性错误 'dict has no attribute "read"'
Python 3.7 JSON - AttributeError 'dict has no attribute "read"'
我正在用 JSON 做一些简单的练习,突然间,我开始发现阻止字典转换为 JSON 并记录在文件中的错误:
import json
i = {
"element" : "some element",
"items" : [
1, "true", "thing"
],
"nested": {
"dfadf": "1",
"adfgf": "2"
}
}
file = json.load(i)
Returns:
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>
我尝试粘贴基本功能代码但出现相同的错误,或者在尝试转储到文件时出现 'write' 错误。我的 Python 的安装是不是坏了? (我用的是公司笔记本,到昨天还好好的)
设置:Windows 10,Python 3.7.4(运行 命令 'py' 不启动 Python 2.7)
非常感谢您的意见!
您必须打开文件并使用 json.dump
将 json 写入该文件
with open("filename.json", 'w+') as file:
json.dump(file, i)
如果文件不存在,参数 w+
将创建文件
如果只想将其转换为字符串而不写入文件,请使用json.dumps
json_content = json.dumps(i)
我正在用 JSON 做一些简单的练习,突然间,我开始发现阻止字典转换为 JSON 并记录在文件中的错误:
import json i = { "element" : "some element", "items" : [ 1, "true", "thing" ], "nested": { "dfadf": "1", "adfgf": "2" } } file = json.load(i)
Returns:
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>
我尝试粘贴基本功能代码但出现相同的错误,或者在尝试转储到文件时出现 'write' 错误。我的 Python 的安装是不是坏了? (我用的是公司笔记本,到昨天还好好的) 设置:Windows 10,Python 3.7.4(运行 命令 'py' 不启动 Python 2.7)
非常感谢您的意见!
您必须打开文件并使用 json.dump
将 json 写入该文件
with open("filename.json", 'w+') as file:
json.dump(file, i)
如果文件不存在,参数 w+
将创建文件
如果只想将其转换为字符串而不写入文件,请使用json.dumps
json_content = json.dumps(i)