gpt4 book ai didi

json - 使用 jq 将 JSON 数组转换为 CSV

转载 作者:行者123 更新时间:2023-12-04 16:30:27 26 4
gpt4 key购买 nike

我有一个名为 temp.json 的 JSON 文件。

{
"users": [
{
"username": "jack",
"email": "jack@somewhere.com",
"total running apps": "1",
"api-mock-app": "0",
"flogo": "1",
"ipaas": "0",
"nodejs-app": "0"
},
{
"username": "jill",
"email": "jill@somewhere.com",
"total running apps": "1",
"api-mock-app": "0",
"flogo": "1",
"ipaas": "0",
"nodejs-app": "0"
}
]
}

我想将此 JSON 转换为类似的 CSV,

username email              total running apps api-mock-app flogo ipaas nodejs-app
jack jack@somewhere.com 1 0 1 0 0
jill jill@somewhere.com 1 0 1 0 0

我试过了

jq -r '.users[] | keys[0] [.username, .email, ."total running apps", ."api-mock-app", .flogo, .ipaas, ."nodejs-app"] | join(", ") | @csv' temp.json`

但是我遇到了错误

q: error (at temp.json:22): Cannot index string with string "jack"`

谁能解释我在哪里犯错,请告诉我正确的答案。

最佳答案

jq解决方案:

jq -r '(.users[0] | keys_unsorted), (.users[] | to_entries | map(.value))|@csv' temp.json

输出:

"username","email","total running apps","api-mock-app","flogo","ipaas","nodejs-app"
"jack","jack@somewhere.com","1","0","1","0","0"
"jill","jill@somewhere.com","1","0","1","0","0"

关于json - 使用 jq 将 JSON 数组转换为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47730946/

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