Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use jq to filter an array that contains both objects and strings?

Tags:

json

jq

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?

like image 484
Kramer Avatar asked Sep 11 '25 07:09

Kramer


1 Answers

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?

like image 88
customcommander Avatar answered Sep 14 '25 00:09

customcommander