gpt4 book ai didi

json - jq 哈希数组到 csv

转载 作者:太空宇宙 更新时间:2023-11-04 09:13:46 33 4
gpt4 key购买 nike

所以我有这样一个数据源:

{
"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

$

使用假参数似乎是一种 hack,然后需要通过 sed 清理才能工作。我如何仅使用 jq 来执行此操作。

最佳答案

与其尝试在数据中放入文字换行符,不如将数据拆分为单独的数组(每行一个所需输出),并将每个数组传递给 @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

关于json - jq 哈希数组到 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51127531/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com