简体   繁体   English

使用jq在json中搜索正则表达式

[英]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. 我有这个json,我想获得适合变量子网的相应子网的id。

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. 由于jq不支持正则表达式。 The only way I found to get the right id is to mixte grep, sed and jq like this : 我发现获得正确id的唯一方法是混合grep,sed和jq,如下所示:

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 ? 有没有办法只使用jq获取id?

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 . 我建议使用containsstartswith 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. 既然你提到正则表达式:最新版本的jq,1.5,包括正则表达式支持(感谢Jeff Mercado指出这一点!),如果你不得不经常处理字符串操作问题,我建议你查看它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM