Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use jq when the response is not a list

My json response is like this.

{
  "level": "info",
  "timestamp": "2022-03-21T16:10:27.060Z",
  "msg": "starting test",
}
{
  "level": "warn",
  "timestamp": "2022-03-21T16:10:27.060Z",
  "msg": "message 2"
}
{
  "level": "error",
  "timestamp": "2022-03-21T16:10:27.060Z",
  "msg": "message 3"
}


I want to extract.

Either 3rd message (or nth message) or the message associated with error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I do this with jq?

>Solution :

Use select to filter by condition

jq 'select(.level == "error")'
{
  "level": "error",
  "timestamp": "2022-03-21T16:10:27.060Z",
  "msg": "message 3"
}

Demo

To extract the message, use the -r option

jq -r 'select(.level == "error").msg'
message 3

Demo


If you want to access the nth object, you may want to use a structure whose items you can count. Using the -s option would turn the input stream into an array. Using the --argjson option enables you using an external (JSON) value for reference:

jq -sr --arg n 2 '.[$n].msg'
message 3

Demo

To directly address the nth element of a stream, use the nth function, in combination with inputs and the -n option to address the entire stream at once:

jq -nr --arg n 2 'nth($n;inputs).msg'
message 3

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading