json 使用 jq 到 csv 问题
json to csv issue using jq
我根据需要使用 jq 将以下 json 转换为 CSV
我的 json 是:
{
"id": 39,
"max_x": null,
"max_y": null,
"min_x": null,
"min_y": null,
"name": "L1",
"space_count": 159,
"spaces": [
{
"account_name": "Westpac",
"ext_ids": [
"5d6043ce3b1a6903ba000021",
"5d6043ce3b1a6903ba000022"
],
"gla": 232,
"gross_rent": 493565.04000000004,
"id": 8955,
"lease_end_time": "2021-09-15T00:00:00.000Z",
"map_unit_no": "GD030A",
"mat_excl_gst": 0,
"mat_growth_rate": null,
"mat_month": "January-2020",
"net_rent": 337459.2,
"unit_no": "030A",
"vertices": [
]
}
],
"svg": null
}
我尝试在终端中使用以下代码转换为 CSV:
cat data1.json | jq -r '.spaces[] | [.account_name,.ext_ids[]] | @csv' | tr -d '"' >> output.csv
结果是:
Westpac,5d6043ce3b1a6903ba000021,5d6043ce3b1a6903ba000022
但我需要这样的结果:
Westpac,5d6043ce3b1a6903ba000021
Westpac,5d6043ce3b1a6903ba000022
你能指导我吗?
下面是 JQ 手册中关于为什么会发生这种情况的简要说明。
the expression [1,2,3]
is not using a built-in syntax for comma-separated arrays, but is instead applying the []
operator (collect results) to the expression 1,2,3
(which produces three different results).
使用变量可以避免这个问题。
.spaces[] | .ext_ids[] as $e | [.account_name, $e] | @csv
我根据需要使用 jq 将以下 json 转换为 CSV
我的 json 是:
{
"id": 39,
"max_x": null,
"max_y": null,
"min_x": null,
"min_y": null,
"name": "L1",
"space_count": 159,
"spaces": [
{
"account_name": "Westpac",
"ext_ids": [
"5d6043ce3b1a6903ba000021",
"5d6043ce3b1a6903ba000022"
],
"gla": 232,
"gross_rent": 493565.04000000004,
"id": 8955,
"lease_end_time": "2021-09-15T00:00:00.000Z",
"map_unit_no": "GD030A",
"mat_excl_gst": 0,
"mat_growth_rate": null,
"mat_month": "January-2020",
"net_rent": 337459.2,
"unit_no": "030A",
"vertices": [
]
}
],
"svg": null
}
我尝试在终端中使用以下代码转换为 CSV:
cat data1.json | jq -r '.spaces[] | [.account_name,.ext_ids[]] | @csv' | tr -d '"' >> output.csv
结果是:
Westpac,5d6043ce3b1a6903ba000021,5d6043ce3b1a6903ba000022
但我需要这样的结果:
Westpac,5d6043ce3b1a6903ba000021
Westpac,5d6043ce3b1a6903ba000022
你能指导我吗?
下面是 JQ 手册中关于为什么会发生这种情况的简要说明。
the expression
[1,2,3]
is not using a built-in syntax for comma-separated arrays, but is instead applying the[]
operator (collect results) to the expression1,2,3
(which produces three different results).
使用变量可以避免这个问题。
.spaces[] | .ext_ids[] as $e | [.account_name, $e] | @csv