3saratoga
3saratoga

Reputation: 21

Using jq to get arrays where a key within the array is equal to a specific value?

I have been practicing with jq play to try to get all the arrays in a list where website is == "google" and create another json list from that.

https://jqplay.org/s/DKNC2mhOLq

jq: error (at :18): Cannot index array with string "website" exit status 5

{
    "items": [
    {
     "name":"name1",
     "id":"1",
     "website":"google"
    },
    {
     "name":"name1",
     "id":"1",
     "website":"google"
    },
    {
     "name":"name1",
     "id":"2",
     "website":"jingle"
    }
    ]

Desired output:

   [
    {
     "name":"name1",
     "id":"1",
     "website":"google"
     },
    {
     "name":"name1",
     "id":"1",
     "website":"google"
     }
   ]

how can I loop through arrays in a list and look for specific values for specific keys? Thanks for any help or ideas you can provide. I am a begginer with JSON and jq.

Upvotes: 2

Views: 4205

Answers (1)

pmf
pmf

Reputation: 36151

Enclose the select with a map, as you want to apply the filter to each array item individually while retaining the surrounding array structure.

jq '.items | map(select(.website == "google"))'
[
  {
    "name": "name1",
    "id": "1",
    "website": "google"
  },
  {
    "name": "name1",
    "id": "1",
    "website": "google"
  }
]

Demo

Upvotes: 7

Related Questions