所以我有一个像这样的数据源:
{
"things": [
{
"thing_name": "Bestco",
"thing_id": 1
},
{
"thing_name": "GreatCo",
"thing_id": 2
},
{
"thing_name": "DressCo",
"thing_id": 3
}
]
}
我想要这样的输出:
$ echo '{"things":[{"thing_name":"Bestco","thing_id":1},{"thing_name":"GreatCo","thing_id":2},{"thing_name":"DressCo","thing_id":3}]}' |
jq -r '.things | map(.thing_name, .thing_id, "\n") | @csv' |
sed -e 's/,"$//g' -e 's/^",//g' -e 's/^"$//g'
"Bestco",1
"GreatCo",2
"DressCo",3
$
使用伪造的参数似乎很容易,然后需要通过sed进行清理才能工作。我怎么只用jq就可以做到这一点。
答案 0 :(得分:2)
与其尝试在数据中添加文字换行符,不如将数据分成单独的数组(每行所需的输出一个),然后将每个传递给@csv
。
s='{"things":[{"thing_name":"Bestco","thing_id":1},{"thing_name":"GreatCo","thing_id":2},{"thing_name":"DressCo","thing_id":3}]}'
jq -r '.things[] | [.thing_name, .thing_id] | @csv' <<<"$s"
...正确发射:
"Bestco",1
"GreatCo",2
"DressCo",3