Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 203
executable Avatar asked May 29 '19 08:05

executable


2 Answers

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
like image 121
Jeff Mercado Avatar answered Oct 01 '22 02:10

Jeff Mercado


If, as suggested by part of the question, you want to confine the search to key names starting with "ext":

.details.addresses
| to_entries[]
| select(.key|startswith("ext"))
| .value[]
| select(.version == 4)
| .addr

Towards the other end of the spectrum of permissiveness:

.details.addresses
| ..
| objects
| select(.version==4)
| .addr
like image 39
peak Avatar answered Oct 01 '22 01:10

peak