Python 'str' 对象没有属性 'read'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19474832/
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
Python 'str' object has no attribute 'read'
提问by CodeGuru
Python 3.3.2 import json & urllib.request
Python 3.3.2 导入 json & urllib.request
Json
杰森
[{"link":"www.google.com","orderid":"100000222"},
{"link":"www.google.com","orderid":"100000222"},
{"link":"www.google.com","orderid":"100000222"}]
print(response.info())
打印(响应。信息())
Date: Sun, 20 Oct 2013 07:06:51 GMT
Server: Apache
X-Powered-By: PHP/5.4.12
Content-Length: 145
Connection: close
Content-Type: application/json
Codes
代码
url = "http://www.Link.com"
request = urllib.request.Request(url)
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib.request.urlopen(request)
decodedRes = response.read().decode('utf-8')
json_object = json.load(decodedRes)
The following are my codes Error
以下是我的代码错误
Traceback (most recent call last):
File "C:\Users\Jonathan\Desktop\python.py", line 57, in <module>
checkLink()
File "C:\Users\Jonathan\Desktop\python.py", line 50, in checkLink
json_object = json.load(decodedRes)
File "C:\Python33\lib\json\__init__.py", line 271, in load
return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
>>> .
Any idea how i can fix this issue?
知道如何解决这个问题吗?
采纳答案by falsetru
Use json.loads
instead of json.load
.
使用json.loads
代替json.load
。
json.loads(decodedRes)
json.load
accept file-like object.
json.load
接受类文件对象。
>>> import json
>>> json.load('{"a": 1}')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\json\__init__.py", line 286, in load
return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
>>> json.loads('{"a": 1}')
{u'a': 1}
Alternatively you can pass response object to json.load
:
或者,您可以将响应对象传递给json.load
:
## decodedRes = response.read().decode('utf-8')
json_object = json.load(response)
回答by feverDream
Try replacing the json.load()
with json.loads()
. The former needs a file-stream thats the reason you are running into the attribute error.
请尝试更换json.load()
用json.loads()
。前者需要一个文件流,这就是您遇到属性错误的原因。
回答by Patel Sunil
It's very simple, You just need to import beautiful soup in another way. Right now you are importing as
很简单,你只需要用另一种方式导入美丽的汤。现在您正在导入为
from beautifulSoup import BeautifulSoup
Change it to
将其更改为
from bs4 import BeautifulSoup
回答by Manikandan
Following code loads json file into document. Document will have values of dict type.
以下代码将 json 文件加载到文档中。文档将具有 dict 类型的值。
file_name = "my_file.json"
with open(file_name, 'r') as f:
document = json.loads(f.read())