0

I am new to JQ, I have below json file

   [
   {
     "userId" : "jens",
     "firstName" : "jens",
     "lastName" : "jens",
     "emailAddress" : "[email protected]",
     "source" : "default",
     "status" : "active",
     "readOnly" : false,
     "roles" : [ "reader" ],
     "externalRoles" : [ ]
   }, {
     "userId" : "admin",
     "firstName" : "Administrator",
     "lastName" : "User",
     "emailAddress" : "[email protected]",
     "source" : "default",
     "status" : "changepassword",
     "readOnly" : false,
     "roles" : [ "app-admin" ],
     "externalRoles" : [ ]
   }]  

Now I want to print as below format

"userId" : "jens","roles" : [ "reader" ]
"userId" : "admin", "roles" : [ "app-admin" ],

How can I achieve this? I tried with this command

jq -r '.[].userId,.[].roles'

but it scatters the data like below

jens
admin
[]
[
  "reader",
  "app-admins",
]

Please guide me how can I have above output.

AdminBee
  • 21,637
  • 21
  • 47
  • 71
Samurai
  • 55
  • 1
  • 7
  • 1
    Does this answer your question? [How to do formatted printing with jq?](https://unix.stackexchange.com/questions/659216/how-to-do-formatted-printing-with-jq) – pLumo May 05 '22 at 06:17
  • Do you want broken invalid JSON as output, or do you want the strings in the original document to also be decoded (`\n` expanded to literal newlines etc.)? Usually, for queries like these, the task is to create CSV or tab-delimited output, which would be a saner and more straightforward request. – Kusalananda May 05 '22 at 09:18

1 Answers1

3

If you do

jq -c '.[] | {userid: .userId, roles: .roles}'

you'll get

{"userid":"jens","roles":["reader"]}
{"userid":"admin","roles":["app-admin"]}

The -c flag will put each object on its own line, so as long as you don't have nested objects, this should do what you want. Post process to e.g. get rid of the braces:

jq -c '.[] | {userid: .userId, roles: .roles}' | sed -e 's/^{//g' -e 's/}$//g'

produces

"userid":"jens","roles":["reader"]
"userid":"admin","roles":["app-admin"]
dirkt
  • 31,679
  • 3
  • 40
  • 73