0

So, say I have this JSON...

[
  {
    "a": "1",
    "blah": "true"
  },
  {
    "b": "2",
    "blah": "false"
  },
  {
    "c": "3",
    "blah": "true"
  }
]

...and then use jq to select certain entries...

jq '.[] | select(.blah=="true)'

I get this...

{
  "a": "1",
  "blah": "true"
}
{
  "c": "3",
  "blah": "true"
}

But I want it to look like...

[
  {
    "a": "1",
    "blah": "true"
  }
  {
    "c": "3",
    "blah": "true"
  }
]

...this, so that I can use indexing to get certain of these entries. How do I do that?

  • Does this answer your question? [How to filter array of objects by element property values using jq?](https://stackoverflow.com/questions/38121740/how-to-filter-array-of-objects-by-element-property-values-using-jq) – knittl Oct 07 '22 at 21:53

3 Answers3

3

Simply indicate you want the result in a list by wrapping the expression with [];

> cat test.json | jq '[.[] | select(.blah=="true")]'

[
  {
    "a": "1",
    "blah": "true"
  },
  {
    "c": "3",
    "blah": "true"
  }
]
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
2

Using map to iterate over the array

jq 'map(select(.blah == "true"))'
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

Using param -s:

jq  '.[]|select(.blah=="true")' | jq -s '.'