0

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?

peak
  • 105,803
  • 17
  • 152
  • 177
Alex Cohen
  • 5,596
  • 16
  • 54
  • 104
  • 3
    Did you already try surrounding it in brackets ```echo $a | jq '[ .[] | select(.location=="Stockholm") ]' ``` – souser Sep 08 '20 at 21:48
  • 2
    BTW, `echo $a` is a frequent cause of heartburn. Always quote your expansions: `echo "$a"`, to avoid [I just assigned a variable, but `echo $variable` shows something else!](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy Sep 08 '20 at 21:57

1 Answers1

2

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"))
Weeble
  • 17,058
  • 3
  • 60
  • 75