Python'str'对象没有属性'read'

编程入门 行业动态 更新时间:2024-10-24 18:17:47
本文介绍了Python'str'对象没有属性'read'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Python 3.3.2 import json& urllib.request

Python 3.3.2 import json & urllib.request

Json

[{"link":"www.google","orderid":"100000222"}, {"link":"www.google","orderid":"100000222"}, {"link":"www.google","orderid":"100000222"}]

print(response.info())

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

代码

url = "www.Link" 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' >>> .

有什么主意我可以解决这个问题吗?

Any idea how i can fix this issue?

推荐答案

使用 json.loads 而不是json.load.

json.loads(decodedRes)

  • 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)

更多推荐

Python'str'对象没有属性'read'

本文发布于:2023-10-16 16:49:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498159.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   对象   Python   read   str

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!