jq 操作字段与正则表达式匹配的对象

问题描述 投票:0回答:1

我需要从树的任意深度的对象中删除一个字段

.xxx
,其中另一个字段
.myfield
与正则表达式匹配。

我知道如何匹配精准的内容:

walk(if type == "object" and .myfield == "my content" then del(.xxx) else . end)'

我了解正则表达式过滤器

select(.myfield | test(my regexp))

如何将该过滤器转换为布尔条件以在

if
子句中使用?

json jq
1个回答
0
投票

您可以在条件中使用

(.myfield | test("my regexp"))
,就像您可以使用 `.myfield == "my content" 一样。

因此:

jq -c '
  walk(if type == "object" and
          .myfield? != null and
          (.myfield | test("my regexp"))
       then del(.xxx)
       else . end)
' <<'EOF'
{
  "structure": {
    "test-match": {
      "myfield": "content that matches my regexp",
      "xxx": "this should be deleted"
    },
    "test-nomatch": {
      "myfield": "content that DOES NOT match the active expression",
      "xxx": "this should not be deleted"
    },
    "test-invalid": {
      "state": "no myfield exists at all",
      "xxx": "this should not be deleted"
    }
  }
}
EOF

...正确地作为输出发出:

{
  "structure": {
    "test-match": {
      "myfield": "content that matches my regexp"
    },
    "test-nomatch": {
      "myfield": "content that DOES NOT match the active expression",
      "xxx": "this should not be deleted"
    },
    "test-invalid": {
      "state": "no myfield exists at all",
      "xxx": "this should not be deleted"
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.