使用jq将JSON数组转换为CSV
问题描述:
我有一个名为temp.json的JSON文件.
I have JSON file called temp.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,
i want to convert this JSON into CSV lilke this,
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"`
任何人都可以解释我在哪里犯错,请让我知道正确的答案.
Can anyone explain where am i making mistake and please let me know the correct answer.
答
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"