首页 > 解决方案 > 将 JSON(嵌套键值)解析为 CSV

问题描述

我有名为 test.json 的 json 文件。它包含

{
    "rl": {
        "entries": [
            {
                "query_value": {
                    "value": "0dedc344b2658a1328de3578"
                },
                "status": "KNOWN"
            },
            {
                "query_value": {
                    "value": "065d451e42bc31363cbe6c"
                },
                "status": "KNOWN"
            },
            {
                "query_value": {
                    "value": "00fb1e5be9df8338833c1c"
                },
                "status": "UNKNOWN"
            }
        ]
    }
}

需要将其解析为 CSV ,在 CSV 中,输出应该是

value                          status
0dedc344b2658a1328de3578       KNOWN
065d451e42bc31363cbe6c         KNOWN
00fb1e5be9df8338833c1c         UNKNOWN

我已经检查了加载到 jsondump,但无法检索属性字段“值”和“状态”

标签: jsonparsingexport-to-csvpython-3.7

解决方案


尝试以下方式:

import json
js_st = """[your json string above]"""
dat = json.loads(js_st)
rows = []
targets = dat['rl']['entries']
for target in targets:
    rows.extend([[target['query_value']['value'],target['status']]])

这将为您提供可以使用标准 python 写入 csv 文件的目标数据行writer.writerows(rows)


推荐阅读