Csv
如何使用 jq 創建帶有來自 JSON 的標頭的 CSV
我正在嘗試使用 jq 創建一個帶有來自 json 的標頭的 csv 文件。
我有以下片段**https://jqplay.org/s/H_U5mxbTFW**
問題: 如何列印和的
peerings > accept_vpc_info > tenant_id
值peerings > accept_vpc_info > vpc_id
我嘗試了什麼:
JSON
{ "peerings": [ { "accept_vpc_info": { "tenant_id": "184a5", "vpc_id": "0d11f" }, "created_at": "2018-11-07T08:53:43", "description": null, "id": "0b19d", "name": "NAME1", "request_vpc_info": { "tenant_id": "08a7b", "vpc_id": "1645f" }, "status": "ACTIVE", "updated_at": "2018-11-07T09:47:44" }, { "accept_vpc_info": { "tenant_id": "067eb", "vpc_id": "17944" }, "created_at": "2019-06-12T08:29:08", "description": null, "id": "0d34a", "name": "NAME2", "request_vpc_info": { "tenant_id": "0fd7b", "vpc_id": "102c9" }, "status": "ACTIVE", "updated_at": "2019-06-12T12:04:56" }, { "accept_vpc_info": { "tenant_id": "0ae21", "vpc_id": "071c4" }, "created_at": "2019-02-21T09:07:35", "description": null, "id": "173e2", "name": "NAME3", "request_vpc_info": { "tenant_id": "05a21", "vpc_id": "0586e" }, "status": "ACTIVE", "updated_at": "2019-02-21T09:10:41" } ] }
JQ:
.[] | flatten | map({created_at,description,id,name,status,updated_at}) | (first | keys_unsorted) as $keys | map([to_entries[] | .value]) as $rows | $keys,$rows[] | join (", ")
它在不添加
accept_vpc_info
and的情況下工作request_vpc_info
。我嘗試將這些添加為標題:
accept_vpc_info
,accept_vpc_info_tenant_id
,accept_vpc_info_vpc_id
,created_at
,description
,id
,name
,request_vpc_info
,request_vpc_info_tenant_id
,request_vpc_info_vpc_id
,status
,updated_at
像這樣的東西:
"accept_vpc_info__tenant_id","accept_vpc_info__vpc_id","created_at","description","id","name","request_vpc_info__tenant_id","request_vpc_info__vpc_id","status","updated_at" "184a5","0d11f","2018-11-07T08:53:43","null","0b19d","NAME1","08a7b","1645f","ACTIVE","2018-11-07T09:47:44" "067eb","17944","2019-06-12T08:29:08","null","0d34a","NAME2","0fd7b","102c9","ACTIVE","2019-06-12T12:04:56" "0ae21","071c4","2019-02-21T09:07:35","null","173e2","NAME3","05a21","0586e","ACTIVE","2019-02-21T09:10:41"
我怎樣才能列印
peerings > accept_vpc_info > tenant_id
和的值peerings > accept_vpc_info > vpc_id
?謝謝
我通常不喜歡在一個應該完成工作時使用兩種工具,但您可能會考慮使用 Miller 的(有限的)JSON 到 CSV 轉換功能 - 這似乎是限制實際上有幫助的一種情況(因為預設情況下它會使所有內容變平,並建構為您展平欄位名稱):
$ mlr --prepipe 'jq ".[]"' --ijson --jflatsep __ --ocsv --quote-all cat file.json "accept_vpc_info__tenant_id","accept_vpc_info__vpc_id","created_at","description","id","name","request_vpc_info__tenant_id","request_vpc_info__vpc_id","status","updated_at" "184a5","0d11f","2018-11-07T08:53:43","","0b19d","NAME1","08a7b","1645f","ACTIVE","2018-11-07T09:47:44" "067eb","17944","2019-06-12T08:29:08","","0d34a","NAME2","0fd7b","102c9","ACTIVE","2019-06-12T12:04:56" "0ae21","071c4","2019-02-21T09:07:35","","173e2","NAME3","05a21","0586e","ACTIVE","2019-02-21T09:10:41"