1

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.

Marcel
  • 1,383
  • 1
  • 12
  • 22
Rajiv Rai
  • 175
  • 2
  • 11
  • Possible duplicate of [Convert a JSON into CSV using jq](https://stackoverflow.com/questions/47715234/convert-a-json-into-csv-using-jq) – knb Dec 10 '17 at 08:59

3 Answers3

3

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"
RomanPerekhrest
  • 73,078
  • 4
  • 37
  • 76
0

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"
Rajiv Rai
  • 175
  • 2
  • 11
0

I think the simplest ways to do it is

jq -r "(.users[0] | keys_unsorted),  (.users[] | map(.) | @csv)"
Phil
  • 3,034
  • 1
  • 18
  • 15