如何在scrapy中设置json输出的键值对?

时间:2014-07-03 07:41:19

标签: python json web-scraping scrapy

[{"Definition": ["Hello World."], "Fast": ["10"], "Free": ["Yes"], "Name": ["Hello"], "Movement": ["Fine"]}]

使用此命令抓取网站后:

scrapy crawl hello -o helloworld.json -t json   

我正在获得上面的格式化输出。我希望名称的值作为json数组的名称出现,因此输出看起来像这样

{"Hello": {"Definition": ["Hello World"],"Fast": ["10"],"Free": ["Yes"], "Movement": ["Fine"]}

是否有可能在scrapy中这样做?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

>>> a = [{"Definition": ["Hello World."], "Fast": ["10"], "Free": ["Yes"], "Name": ["Hello"], "Movement": ["Fine"]}]
>>> b = {a[0]['Name'][0]:a[0].copy()} # copy optional
del b[a[0]['Name'][0]]['Name']
>>> b
{'Hello': {'Definition': ['Hello World.'], 'Fast': ['10'], 'Free': ['Yes'], 'Movement': ['Fine']}}

根据您的评论进行修改:

>>> a = [{"Definition": ["Hello World."], "Fast": ["10"], "Free": ["Yes"], "Name": ["Hello"], "Movement": ["Fine"]}]
>>> b = {a[0]['Name'][0]:{k:v[0] for k,v in a[0].items()}}
>>> del b[a[0]['Name'][0]]['Name']
>>> b
{'Hello': {'Definition': 'Hello World.', 'Fast': '10', 'Free': 'Yes', 'Movement': 'Fine'}}