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.

2
  • 1
    Does this answer your question? How to do formatted printing with jq?
    – pLumo
    May 5, 2022 at 6: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 5, 2022 at 9:18

1 Answer 1

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"]
1
  • it helped thank you so much,
    – Samurai
    May 5, 2022 at 9:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .