【问题标题】:Attribute error: 'bytes' object has no attribute '__dict__'属性错误:“字节”对象没有属性“__dict__”
【发布时间】:2019-07-26 15:40:55
【问题描述】:

我正在尝试将从 API 接收到的数据保存在 json 格式的文件中。

response = requests.get(url_league,   headers= header)
type(response)
#output requests.models.Response
with open("json.txt", "w+") as f:
    data = json.dump(response, f)

当我尝试将响应对象保存到文件时,出现以下错误

Object of type Response is not JSON serializable

我读到 json 模块在编码复杂对象方面存在问题,为此目的,json 具有编码复杂对象的默认函数。我尝试了以下代码

json_data = json.dump(response.__dict__, f, default = lambda o: o.__dict__, indent=4)

并得到以下错误

bytes' object has no attribute '__dict__'

这个错误是什么意思以及如何解决?

【问题讨论】:

  • 你试过使用response.json()吗?
  • Wonderfull) 我试过了,得到了我想要的。谢谢大佬

标签: python json python-requests


【解决方案1】:

您收到的错误意味着响应是“字节”类型,而不是文本/JSON。您需要先解码您的响应(您需要 urllib 或 urllib2)。

import json
import urllib.request

response=urllib.request.urlopen(url_league).read()
string = response.decode('utf-8')
json_obj = json.loads(string)

with open("json.txt", "w+") as f:
    data = json.dump(json_obj, f)

要使用标题,您可以使用

req = Request(url)
req.add_header('apikey', 'xxx')

【讨论】:

    猜你喜欢
    • 2017-12-29
    • 2017-12-20
    • 2011-11-21
    • 2019-12-02
    • 2014-05-14
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    相关资源
    最近更新 更多