You can filter JSON data using jq based on multiple conditions (fields/keys) using the select() function.
Create some dummy JSON data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
## Create a sample json data cat << EOF > data.json [ { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular" }, { "id": "1002", "type": "Chocolate" }, { "id": "1003", "type": "Blueberry" }, { "id": "1004", "type": "Chocolate" } ] } } ] EOF |
Select specific elements on JSON data based on key values (condition) using jq:
1 2 3 4 5 6 7 8 9 10 11 |
cat data.json | jq -r '.[].batters.batter[] | select(.type=="Chocolate")' ## returns ## { ## "id": "1002", ## "type": "Chocolate" ## } ## { ## "id": "1004", ## "type": "Chocolate" ## } |
Filter JSON data with when condition and select specific keys:
1 2 3 4 5 |
cat data.json | jq -r '.[].batters.batter[] | select(.type=="Chocolate") | .id' ## returns ## 1002 ## 1004 |
Filter JSON data based on multiple conditions using JQ:
1 2 3 4 5 6 7 |
cat data.json | jq -r '.[].batters.batter[] | select((.type=="Chocolate") and (.id=="1004"))' ## returns ## { ## "id": "1004", ## "type": "Chocolate" ## } |