使用 jqplay 将 json 展平为 csv

flattening json to csv with jqplay

我正在尝试将 json 文件压缩为 .csv。例如,我想为此使用 jqplay 而不是在 python 中对其进行编程。 下面的示例是 als 包含数组的数组。 我想要的输出是第二个数组中的一行条目: 所以

打开,NR1,....

关闭,NR2,...

.....

任何人都可以帮我提供一个好的 jq 命令吗?

[
    {
        "description": "Berendrechtsluis",
        "lock_id": "BES",
        "longitude_wgs84": 4.28561,
        "latitude_wgs84": 51.34414,
        "lock_doors": [
            {
                "state": "OPEN",
                "lock_door_id": "NR1",
                "operational_state": "NO_DATA",
                "state_since_in_utc": "2021-12-29T16:32:23Z",
                "longitude_wgs84": 4.28214,
                "latitude_wgs84": 51.34426
            },
            {
                "state": "CLOSED",
                "lock_door_id": "NR2",
                "operational_state": "WORKING",
                "state_since_in_utc": "2022-01-12T12:32:52Z",
                "operational_state_since_in_utc": "2021-12-22T13:13:57Z",
                "longitude_wgs84": 4.28247,
                "latitude_wgs84": 51.34424
            },
            ....

你在找这样的东西吗?

jq -r '.[].lock_doors[] | [.[]] | @csv'
"OPEN","NR1","NO_DATA","2021-12-29T16:32:23Z",4.28214,51.34426
"CLOSED","NR2","WORKING","2022-01-12T12:32:52Z","2021-12-22T13:13:57Z",4.28247,51.34424

Demo

要添加列 headers,只需将它们添加到数组中:

jq -r '["a","b","c"], .[].lock_doors[] | [.[]] | @csv'
"a","b","c"
"OPEN","NR1","NO_DATA","2021-12-29T16:32:23Z",4.28214,51.34426
"CLOSED","NR2","WORKING","2022-01-12T12:32:52Z","2021-12-22T13:13:57Z",4.28247,51.34424

Demo