【问题标题】:TypeError: Object of type 'bytes' is not JSON serializableTypeError:“字节”类型的对象不是 JSON 可序列化的
【发布时间】:2017-11-24 16:58:20
【问题描述】:

我刚开始编写 Python。我想用scrapy创建一个机器人,结果显示 TypeError:当我运行项目时,'bytes' 类型的对象不是 JSON 可序列化的。

import json
import codecs

class W3SchoolPipeline(object):

  def __init__(self):
      self.file = codecs.open('w3school_data_utf8.json', 'wb', encoding='utf-8')

  def process_item(self, item, spider):
      line = json.dumps(dict(item)) + '\n'
      # print line

      self.file.write(line.decode("unicode_escape"))
      return item

from scrapy.spiders import Spider
from scrapy.selector import Selector
from w3school.items import W3schoolItem

class W3schoolSpider(Spider):

    name = "w3school"
    allowed_domains = ["w3school.com.cn"]

    start_urls = [
        "http://www.w3school.com.cn/xml/xml_syntax.asp"
    ]

    def parse(self, response):
        sel = Selector(response)
        sites = sel.xpath('//div[@id="navsecond"]/div[@id="course"]/ul[1]/li')

    items = []
    for site in sites:
        item = W3schoolItem()
        title = site.xpath('a/text()').extract()
        link = site.xpath('a/@href').extract()
        desc = site.xpath('a/@title').extract()

        item['title'] = [t.encode('utf-8') for t in title]
        item['link'] = [l.encode('utf-8') for l in link]
        item['desc'] = [d.encode('utf-8') for d in desc]
        items.append(item)
        return items

追溯:

TypeError: Object of type 'bytes' is not JSON serializable
2017-06-23 01:41:15 [scrapy.core.scraper] ERROR: Error processing       {'desc': [b'\x
e4\xbd\xbf\xe7\x94\xa8 XSLT \xe6\x98\xbe\xe7\xa4\xba XML'],
 'link': [b'/xml/xml_xsl.asp'],
 'title': [b'XML XSLT']}

Traceback (most recent call last):
File  
"c:\users\administrator\appdata\local\programs\python\python36\lib\site-p
ackages\twisted\internet\defer.py", line 653, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
File "D:\LZZZZB\w3school\w3school\pipelines.py", line 19, in process_item
    line = json.dumps(dict(item)) + '\n'
File 
"c:\users\administrator\appdata\local\programs\python\python36\lib\json\_
_init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
File 
"c:\users\administrator\appdata\local\programs\python\python36\lib\json\e
ncoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
File  
"c:\users\administrator\appdata\local\programs\python\python36\lib\json\e
ncoder.py", line 257, in iterencode
    return _iterencode(o, 0)
File      
"c:\users\administrator\appdata\local\programs\python\python36\lib\
json\encoder.py", line 180, in default
    o.__class__.__name__)
  TypeError: Object of type 'bytes' is not JSON serializable

【问题讨论】:

    标签: python json serialization scrapy


    【解决方案1】:

    我在处理图像数据时遇到了同样的错误。在 Python 中,在客户端,我正在读取一个图像文件并将其发送到我的服务器。我的服务器将二进制数据解码为字节。所以,我只是将我的字节数据转换成一个字符串来解决我的错误。

    image_bytes =  file.read()
    data = {"key1": "value1", "key2" :  "value2", "image" : str(image_bytes)}
    

    【讨论】:

      【解决方案2】:

      只需写<variable name>.decode("utf-8")

      例如:

      myvar = b'asdqweasdasd'
      myvar.decode("utf-8")
      

      【讨论】:

      • 这是不可能的,在给定的例子中,你可以做到myvar = b'asdqweasdasd'但是如果myvar = random.randbytes(50)
      【解决方案3】:

      我今天正在处理这个问题,我知道我有一些编码为字节对象的东西,我试图用json.dump(my_json_object, write_to_file.json) 将其序列化为 json。 my_json_object 在这种情况下是我创建的一个非常大的 json 对象,所以我有几个字典、列表和字符串要查看以查找仍然是字节格式的内容。

      我最终解决它的方式:write_to_file.json 将包含导致问题的字节对象的所有内容。

      在我的特殊情况下,这是通过

      获得的一条线
      for line in text:
          json_object['line'] = line.strip()
      

      我首先在 write_to_file.json 的帮助下找到此错误,然后将其更正为:

      for line in text:
          json_object['line'] = line.strip().decode()
      

      【讨论】:

        【解决方案4】:

        您正在自己创建这些 bytes 对象:

        item['title'] = [t.encode('utf-8') for t in title]
        item['link'] = [l.encode('utf-8') for l in link]
        item['desc'] = [d.encode('utf-8') for d in desc]
        items.append(item)
        

        每个t.encode()l.encode()d.encode() 调用都会创建一个bytes 字符串。不要这样做,留给 JSON 格式来序列化这些。

        接下来,你又犯了几个错误;您在不需要的地方编码太多。将其留给json 模块和由open() 调用返回的标准 文件对象来处理编码。

        您也不需要将items 列表转换为字典;它已经是一个可以直接进行 JSON 编码的对象了:

        class W3SchoolPipeline(object):    
            def __init__(self):
                self.file = open('w3school_data_utf8.json', 'w', encoding='utf-8')
        
            def process_item(self, item, spider):
                line = json.dumps(item) + '\n'
                self.file.write(line)
                return item
        

        我猜你遵循了假设 Python 2 的教程,而你正在使用 Python 3。我强烈建议你找一个不同的教程;它不仅是为过时的 Python 版本编写的,如果它提倡 line.decode('unicode_escape'),它正在教一些非常坏的习惯,这些习惯会导致难以跟踪的错误。我可以推荐您查看Think Python, 2nd edition,这是一本关于学习 Python 3 的免费好书。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-14
          • 2021-03-11
          • 2019-11-21
          • 2021-11-13
          相关资源
          最近更新 更多