Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex-like search in a json with jq

Tags:

I have this json and I want to get the id of the corresponding subnet that fit the variable subnet.

subnet="192.168.112" json='{   "subnets": [     {       "cidr": "192.168.112.0/24",       "id": "123"     },     {       "cidr": "10.120.47.0/24",       "id": "456"     }   ] }' 

Since regex is not supported with jq. The only way I found to get the right id is to mixte grep, sed and jq like this :

tabNum=$((`echo ${json} | jq ".subnets[].cidr" | grep -n "$subnet" | sed "s/^\([0-9]\+\):.*$/\1/"` - 1)) NET_ID=`echo ${json} | jq -r ".subnets[${tabNum}].id"` 

Is there a way to get the id only using jq ?