简体   繁体   中英

Convert JSON array into CSV using jq

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"
    }
  ]
}

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

I tried this

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

But i am getting error

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 solution:

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

The output:

"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[0] | keys_unsorted),  (.users[] | map(.) | @csv)"

I tried this, and it worked perfectly,

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

output format is.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM