[英]Convert Json to CSV by jq filter
我有一個包含此內容的 json 文件,並希望將其轉換為 CSV,如下所示:
{
"fields": [
{
"id": 17,
"name": "Business Division",
"values": [
{
"id": 131,
"name": "Accounting",
"industry": [
"Accounting"
]
}
]
},
{
"id": 16,
"name": "Cancellation Reason",
"values": [
{
"id": 114,
"name": "Forgot"
}
]
}
]
}
CSV 文件格式:
17,Business Division,131,Accounting,Accounting
16,Cancellation Reason,114,Forgot
我在終端上運行了這個命令:
jq -M -r -f industry.jq source.json |tr -d '"' >source.csv
這是用作過濾器的行業.jq 文件的內容:
.fields[]
| .values[] as $e
| $e.industry[]? as $s
| [.id, .name, $e.id, $e.name, $s? ]
| @csv
As result, the second line of the CSV file did not print I think it's because of the.industry[] object that did not available in the second object in my Json
如何以所需格式打印上述 json?
.fields[] | [ .id, .name, .values[].id, .values[].name, .values[].industry[]? ] | @csv
會產生
17,"Business Division",131,"Accounting","Accounting"
16,"Cancellation Reason",114,"Forgot"
當像這樣調用時:
jq --raw-output '.fields[] | [ .id, .name, .values[].id, .values[].name, .values[].industry[]? ] | @csv'
后面會加入多個行業
我會使用try... catch...
使默認值顯式,例如
(try $e.industry[] catch null) as $s
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.