json文件注意事项

来源:互联网 发布:甲骨文数据库培训 编辑:程序博客网 时间:2024/05/16 08:36
在写入json文件时,一般文件内容将会出现是二进制,文字不显示,,
解决方法:
在json转换时.
代码:
import json
import codecs 使用这个模块打开文件解决大多数的编码问题
 self.file =codecs.open('article.json','w',encoding='utf-8') 打开文件并创建
json.dumps(dict,ensure_ascii=False)  这里注意第一参数是字典,ensure_ascii这里设置成False是转换编码

在scrapy本身也提供写入json的机制(可以让我们很方便的将item导成各种文件)
导入模块:
from  scrapy.exporters import JsonItemExporter
例:
class JsonExporterPipeline(object):
#调用scrapy提供的json export导出json文件
def __init__(self):
self.file = open('articleexproter.json'm','wb',)  #打开一个文件
self.exporter = jsonitemexporter(self.file,encoding='utf-8',ensure-ascii=False)  #实例化,,传递参数并设置编码
self.exporter.start_exporting()  #调用这个函数
def close_spider(self,spider):
self.exporter.finish_exporting()   #调用。。停止导出
self.file.close()   #关闭
def  process_item(self,item,spider):
self.exporter.export_item(item)  #将item传入
return item   #返回item
原创粉丝点击