Python“str”对象没有属性“read”

2024-04-29

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"}]

打印(响应.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)

以下是我的代码 错误

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'
>>> .

知道如何解决这个问题吗?


Use json.loads http://docs.python.org/2/library/json.html#json.loads代替json.load.

json.loads(decodedRes)
  • json.load http://docs.python.org/2/library/json.html#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}

或者,您可以将响应对象传递给json.load:

## decodedRes = response.read().decode('utf-8')
json_object = json.load(response)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python“str”对象没有属性“read” 的相关文章

随机推荐