mguerin mguerin - 5 months ago 30
JSON Question

regex-like search in a json with jq

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 ?

Answer

It's not completely clear to me what your provided script does, but it seems like it only looks for a string that contains the provided subset. I would suggest using contains or startswith. A sample script would look like:

echo "${json}" | jq --arg subnet "$subnet" '.subnets[] | select(.cidr | startswith($subnet)).id'

Since you mention regex: the latest release of jq, 1.5, includes regex support (thanks to Jeff Mercado for pointing this out!) and, if you have to deal with string manipulation problems frequently, I'd recommend checking it out.