【问题标题】:Python 'str' object has no attribute 'read'Python 'str' 对象没有属性 'read'
【发布时间】:2013-10-28 18:47:31
【问题描述】:

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

打印(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 = "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'
>>> .

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

【问题讨论】:

    标签: php python arrays json python-3.x


    【解决方案1】:

    使用json.loads 代替json.load

    json.loads(decodedRes)
    

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

    【讨论】:

      【解决方案2】:

      以下代码将 json 文件加载到文档中。文档将具有 dict 类型的值。

      file_name = "my_file.json"
      with open(file_name, 'r') as f:
          document =  json.loads(f.read())
      

      【讨论】:

        【解决方案3】:

        尝试将 json.load() 替换为 json.loads() 。前者需要一个文件流,这就是您遇到属性错误的原因。

        【讨论】:

          【解决方案4】:

          很简单,你只需要用另一种方式导入漂亮的汤。 现在您正在导入为

          from beautifulSoup import BeautifulSoup
          

          改成

          from bs4 import BeautifulSoup
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-03-02
            • 1970-01-01
            • 2020-09-28
            • 2021-08-25
            • 2017-06-04
            相关资源
            最近更新 更多