# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from __future__ import unicode_literals
import json
from scrapy.exceptions import DropItem


class JsonWriterPipeline(object):
    def open_spider(self, spider):
        self.file = open('items.json', 'w')

    def close_spider(self, spider):
        self.file.close()

    def process_item(self, item, spider):
        try:
            if (item['title'] and item['link'] and item['desc']):
                line = json.dumps(dict(item), ensure_ascii=False) + "\n"
                self.file.write(line)
                return item
        except KeyError:
            raise DropItem("Missing field in %s" % item)
