4

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?

0

4 Answers 4

6

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Probably no less efficient, and the verbosity clarifies intent, so I would call this a perfectly good option.
4

There are a few options.


Ignore errors using ?:

map(select(.b? == 2))

docs, jqplay


Check the value's type in your select filter:

map(select(type == "object" and .b == 2))

docs, jqplay


Filter out non-objects:

map(objects | select(.b == 2))

docs, jqplay

Comments

2

Just as @hobbs suggested, use a ? to skip entries that doesn't have a .b.


As of the second question, I'd use map() so the result is an array as requested:

map(select(.b? == 2))
[
  {
    "a": 1,
    "b": 2
  },
  {
    "a": 2,
    "b": 2
  }
]

Try it online!

Comments

1

You can just add a ?: .[]| select(.b? == 2).

From the docs:

Optional Object Identifier-Index: .foo?

Just like .foo, but does not output even an error when . is not an array or an object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.