使用jq将JSON数组转换为CSV

时间:2017-12-09 17:01:36

标签: json csv jq

我有一个名为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 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"`

任何人都可以解释我在哪里犯了错误,请让我知道正确答案。

3 个答案:

答案 0 :(得分:2)

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"

答案 1 :(得分:0)

我试过这个,它运作得很好,

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

输出格式为。

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

答案 2 :(得分:0)

我认为最简单的方法是

jq -r "(.users[0] | keys_unsorted),  (.users[] | map(.) | @csv)"