过滤json并将输出写入cs

2024-10-05 10:21:26 发布

您现在位置:Python中文网/ 问答频道 /正文

如何过滤出JSON文件的特定键值对并将其余部分写入CSV?在

例如,过滤掉headerName键并将URL, Domain, Pages写入CSV文件:

[{"URL": "http://help.abc.com/", "headerName": Null, "Domain": "www.abc.com", "Pages": "27"},
 {"URL": "https://support.bcd.com/", "headerName": Null, "Domain": "www.bcd.com", "Pages": "15"}]

这将产生:

^{pr2}$

Tags: 文件csvcomjsonhttpurldomainwww
1条回答
网友
1楼 · 发布于 2024-10-05 10:21:26

使用^{} instance处理将这些写入文件的操作,将URLDomain和{}作为字段名,并将extrasaction参数设置为'ignore'

The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

[...]

If the dictionary passed to the writerow() method contains a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to 'raise' a ValueError is raised. If it is set to 'ignore', extra values in the dictionary are ignored.

然后,您可以直接将字典列表传递给writer.writerows()方法:

import csv
import json

with open(outputfilename, 'wb') as outfile:
    writer = csv.DictWriter(outfile,
        fieldnames=('URL', 'Domain', 'Pages'),
        extrasaction='ignore')

    your_json_list = json.loads(your_json_string)
    writer.writerows(your_json_list)

相关问题 更多 >

    热门问题