json序列化问题
发现不用重写 json.JSONEncoder
今天写爬虫处理 item 时
使用ubuntu16.4,python3 ,scrapy
报出错误: TypeError: Object of type 'PangciItem' is not JSON serializable
是 json序列化问题,然后自己在网上查,大部分的解决方法是自定义类并重写 json.JSONEncoder
错误代码 21 行:
实验 print( type(item) ) <放与 函数 process_item 中>
发现item不是字典类型的,于是考虑到将 item 转换 成字典
def process_item(self, item, spider):
print(type(item))
dic = dict(item)
print(type(dic))
data = json.dumps(dic,ensure_ascii=False)
//并成一行是data = json.dumps(dict(item),ensure_ascii=False)
self.file.write(data)
return item
操作成功,运行不在报 json 序列化错误。
是数据类型的问题,json.dumps 操作字典类型数据可自行序列化,
其他的数据类型 需要自己处理,序列化