Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JQ to filter JSON by value

JQ to filter JSON by value

Syntax: cat <filename> | jq -c '.[] | select( .<key> | contains("<value>"))'

Example: To get json record having _id equal 611

cat my.json | jq -c '.[] | select( ._id | contains(611))'

Remember: if JSON value has no double quotes (eg. for numeric) to do not supply in filter i.e. in contains(611)

@jalkjaer
Copy link

jalkjaer commented Sep 17, 2018

if searching for exact value don't use contains as that is substring/array lookup )
use ==
i.e.

cat my.json | jq -c '.[] | select( ._id == 611 ) 

And if your input is not a large array, but rather individual lines of json then use

cat my.json | jq -c 'select( ._id == 611 ) 

@mikeschinkel
Copy link

mikeschinkel commented Jan 2, 2019

Nice! Thanks.

@pmithil7
Copy link

pmithil7 commented Oct 2, 2019

This is helpful. Can we add two select statements and do a 'AND' or an 'OR' of those select statements?

@pmithil7
Copy link

pmithil7 commented Oct 2, 2019

I'm answering my own question. It is possible by piping one select statement into another for an AND operation. Not sure about the OR.

@shillbit
Copy link

shillbit commented Apr 12, 2020

you're a life saver... thanks

@aldnav
Copy link

aldnav commented Jun 17, 2020

I'm answering my own question. It is possible by piping one select statement into another for an AND operation. Not sure about the OR.

You can also use or and and within select.

cat my.json | jq -c '.[] | select( ._id == 611 or .author == "John Doe" )'

https://stedolan.github.io/jq/manual/#ConditionalsandComparisons

@fcgomes92
Copy link

fcgomes92 commented Apr 22, 2021

Thanks a lot for this and for the answers ❤️

@ST-DDT
Copy link

ST-DDT commented Oct 7, 2021

Note: If you need the output to be an array, then you should use map:

cat my.json | jq -c 'map( select( ._id == 611 ) )'

@tripleee
Copy link

tripleee commented Mar 15, 2022

Tangentially, as ever, you want to avoid the useless cat.

Instead of

cat file | jq ...

you want

jq ... file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment