【问题标题】:regex-like search in a json with jq使用 jq 在 json 中进行类似正则表达式的搜索
【发布时间】:2015-07-15 18:16:33
【问题描述】:

我有这个 json,我想获取适合变量子网的相应子网的 id。

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

因为 jq 不支持正则表达式。我发现获得正确 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"`

有没有办法只使用 jq 获取 id ?

【问题讨论】:

  • jq 1.5 支持正则表达式。考虑使用它。

标签: json regex bash jq


【解决方案1】:

我并不完全清楚您提供的脚本做了什么,但它似乎只查找包含所提供子集的字符串。我建议使用containsstartswith。示例脚本如下所示:

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

既然您提到了正则表达式:jq 的最新版本 1.5 包括正则表达式支持(感谢 Jeff Mercado 指出这一点!),如果您必须经常处理字符串操作问题,我建议您检查一下.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    相关资源
    最近更新 更多