Search code examples
jsonselectkeyjqwildcard

How to use jq wildcard


I have the following json:

{  
   "details":{  
      "car": "bmw",
      "addresses":{  
         "ext-118-21-8-0-29":[  
            {  
               "version":4,
               "addr":"89 Psr"
            },
            {  
               "version":6,
               "addr":"56 apT"
            }
         ]
      }
   }
}

The key ext-118-21-8-0-29 is dynamic it will change the next time and I don't know the exact value, that's why I need to use wildcard. I need to get the value of the key addr where version is 4.

I'm expectig as output 89 Psr

I tried the following using the function startswith().

jq '.detail.addresses | select(startswith("ext"))'

But it end with an error.

jq: error (at :0): startswith() requires string inputs


Solution

  • If you don't care about the keys in the object you're searching, you could just search the values of the object using [] which you could then filter to your desired results.

    .details.addresses[][] | select(.version == 4).addr
    

    If on the other hand you wanted to select keys that has a version 4, you could use to_entries to do this:

    .details.addresses | to_entries[] | select(any(.value[]; .version == 4)).key