Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQ: How to turn output of array selector back into an array? [duplicate]

Tags:

json

arrays

jq

I'm using the select function with jq to parse for items in a list that contain a certain value. I want the resulting output to be a json list, but jq gives me the objects individually:

Example:

$ a='{                                                                                   
  "FOO": {                                                                                    
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  },
  "BAZ": {
    "name": "Jack",
    "location": "Whereever"
  }
}'

$ echo $a | jq '.[] | select(.location=="Stockholm")' 
{
  "name": "Donald",
  "location": "Stockholm"
}
{
  "name": "Walt",
  "location": "Stockholm"
}

Instead I want the output to be a json list like this:

[  
  {
    "name": "Donald",
    "location": "Stockholm"
  },
  {
    "name": "Walt",
    "location": "Stockholm"
  }
]

How can I do this with jq?

like image 622
Alex Cohen Avatar asked Sep 05 '25 03:09

Alex Cohen


1 Answers

In general, you can stick square brackets around any expression to gather all its outputs into an array.

[.[] | select(.location=="Stockholm")]

Sometimes it makes sense not to break up the input array in the first place, but use map to transform it:

map(select(.location=="Stockholm"))
like image 181
Weeble Avatar answered Sep 07 '25 21:09

Weeble