So I have this input to jq:
[
"foo",
{
"a": 1,
"b": 2
},
{
"a": 1,
"b": 3
},
{
"a": 2,
"b": 2
}
]
and I want to select all objects where b is 2 ideally as an array:
[
{
"a": 1,
"b": 2
},
{
"a": 2,
"b": 2
}
]
But the string in the list makes that difficult.
If I try:
.[]| select(.b == 2)
Then I get the error:
jq: error (at /tmp/data.json:14): Cannot index string with string "b"
Any help?
Other answers have suggested using ?
which is very good. Another way is to use the built-in objects
filter which discards an input if it is not an object:
map(objects | select(.b == 2))
# ^^^^^^^ ^^^^^^^^^^^^^^^
# A B
A: filter out non-objects
B: At this point, we're dealing with objects
Slightly more verbose and perhaps less efficient?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With