已经看到很多线程,但无法找到我的解决方案。我想在 Python 2.7 中将一个嵌套的 JSON 转换为 CSV。示例 JSON 文件如下:
sample.json # My JSON file that mainly contains a firewall rule
"rulebase": [
{
"from": 1,
"name": "test-policy",
"rulebase": [
{
"action": "6c488338-8eec-4103-ad21-cd461ac2c473",
"action-settings": {},
"comments": "FYI",
"content": [
"97aeb369-9aea-11d5-bd16-0090272ccb30"
],
"content-direction": "any",
"content-negate": false,
"custom-fields": {
"field-1": "",
"field-2": "",
"field-3": ""
},
"destination": [
"97aeb369-9aea-11d5-bd16-0090272ccb30"
],
从上面的 JSON 文件中,我要求将键 {uid、name、rule-number、comments、destination、source、hits.last-date} 等及其值基本上重定向到 CSV。
按照下面的代码,我能够生成 CSV,但似乎只是解析标题,没有别的。
import json
import csv
def get_leaves(item, key=None):
if isinstance(item, dict):
leaves = []
for i in item.keys():
leaves.extend(get_leaves(item[i], i))
return leaves
elif isinstance(item, list):
leaves = []
for i in item:
leaves.extend(get_leaves(i, key))
return leaves
else:
return [(key, item)]
with open('sample.json') as f_input, open('output.csv', 'wb') as f_output:
csv_output = csv.writer(f_output)
write_header = True
for entry in json.load(f_input):
leaf_entries = sorted(get_leaves(entry))
if write_header:
csv_output.writerow([k for k, v in leaf_entries])
write_header = False
csv_output.writerows([v for k, v in leaf_entries.items()])
请指导我,因为我对 Python 脚本非常陌生。
相关分类