【问题标题】:Modify json in the scrapy pipeline在scrapy管道中修改json
【发布时间】:2016-03-11 17:11:15
【问题描述】:

如果我有一个 json/字典(在一个 scrapy 管道中),我将如何在开始时将所有内容添加到键中并去掉括号?

[
  {
    "date":"2015-11-25",
    "threat_level_id":"1",
    "info":"TEST",
    "analysis":"0",
    "distribution":"0",
    "orgc":"Malware, Inc",
    "Attribute":[
      {
        "type":"md5",
        "category":"Payload delivery",
        "to_ids":true,
        "distribution":"3",
        "value":"35b759347aee663e36f5b91877749349"
      }
    ]
  }
]

我想在它的开头添加一个键并去掉括号使其看起来像这样-

{
  "Event":{
    "date":"2015-11-25",
    "threat_level_id":"1",
    "info":"TEST",
    "analysis":"0",
    "distribution":"0",
    "orgc":"Oxygen",
    "Attribute":[
      {
        "type":"md5",
        "category":"Payload delivery",
        "to_ids":true,
        "distribution":"3",
        "value":"35b759347aee663e36f5b91877749349"
      }
    ]
  }
}

感谢 natdempk!

我收到异常。TypeError: 预期的字符串或缓冲区 -

class JsonPipeline(object):
    def process_item(self, item, spider):
        data = json.loads(item)
        new_data = {}
        new_data['Event'] = data
        item = json.dumps(data)
        return item

我正在像这样运行 scrapy 爬虫 - scrapy crawl spider -o items.json

这可行,但我在 _get_serialized_fields 中收到错误文件“/usr/lib/pymodules/python2.7/scrapy/contrib/exporter/init.py”,第 71 行 field = item.fields[field_name] exceptions.AttributeError: 'dict' 对象没有属性 'fields'

class JsonWithEncodingPipeline(object):
    def process_item(self, item, spider):
        data = {}
        data['Event'] = item
        return data

如果我将它添加到 settings.py 中,它可以工作,但我没有得到文件输出?? :(

EXTENSIONS = {'scrapy.contrib.feedexport.FeedExporter': None}

有没有办法在不禁用 FEEDEXPORTER 的情况下做到这一点?

【问题讨论】:

  • 读回来,做你需要的修改,然后保存新数据...

标签: python arrays json dictionary scrapy


【解决方案1】:

您可以使用 Python 的 json 模块将 json 读入字典,然后修改该字典并再次将其导出为 json。

这可能看起来像:

import json

data = json.loads(your_json_data_as_string)

new_data = {}
new_data['Event'] = data

new_json_string = json.dumps(new_data)

这将产生类似于您想要的示例的内容,它将整个给定的 json 数据结构放在键 Event 下。

【讨论】:

  • 在上面进行了编辑,natdempk 你肯定改进了它!仍然得到我认为是 json 错误。还有其他想法吗?
  • 您的其他问题似乎与此有关:github.com/scrapy/scrapy/issues/86 根据阅读该问题,您可能正在尝试将某些内容转换为 JSON 不可序列化的 JSON,例如 Python 日期时间或其他内容.如果没有看到您的数据,很难说是哪条数据导致了问题@mathurin68
猜你喜欢
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 2011-07-11
  • 1970-01-01
相关资源
最近更新 更多