Python 'dict' 对象没有属性 'read'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27415193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'dict' object has no attribute 'read'
提问by Galen
What is wrong with my code?
我的代码有什么问题?
>>> import json
>>> array = json.load({"name":"Galen","learning objective":"load json files for data analysis"})
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
array = json.load({"name":"Galen","learning objective":"load json files for data analysis"})
File "C:\Python34\lib\json\__init__.py", line 265, in load
return loads(fp.read(),
AttributeError: 'dict' object has no attribute 'read'
采纳答案by Archit Verma
Since you want to convert it into json
format, you should use json.dumps()
instead of json.load()
. This would work:
既然你想把它转换成json
格式,你应该使用json.dumps()
而不是json.load()
. 这会起作用:
>>> import json
>>> array = json.dumps({"name":"Galen","learning objective":"load json files for data analysis"})
>>> array
'{"learning objective": "load json files for data analysis", "name": "Galen"}'
Output:
输出:
>>> a = json.loads(array)
>>> a["name"]
u'Galen'
回答by Marcin
I think you are after this:
我认为你在追求这个:
import json
array = json.dumps({"name":"Galen","learning objective":"load json files for data analysis"})
print(array)
Gives:
给出:
{"learning objective": "load json files for data analysis", "name": "Galen"}
回答by Gerardo
if you want to load json from a string you need to add quotes around your string and there is a different method to read from file or variable. For variable it ends with "s" other doesn't
如果您想从字符串加载 json,您需要在字符串周围添加引号,并且有一种不同的方法可以从文件或变量中读取。对于变量,它以“s”结尾,其他不
import json
my_json = '{"my_json" : "value"}'
res = json.loads(my_json)
print res
回答by lauralacarra
As you said, it is wrong, you forgot the ' before and after the json text.
正如你所说,这是错误的,你忘记了json文本前后的'。
import json
array = json.load('{"name":"Galen","learning objective":"load json files for data analysis"}')
I had the same mistake :)
我有同样的错误:)
dumps works but it is not the same. Load is better for parsing json. https://docs.python.org/2/library/json.html
转储有效,但不一样。Load 更适合解析 json。 https://docs.python.org/2/library/json.html