【问题标题】:Using jq, remove keys that match a regular expression使用 jq,删除匹配正则表达式的键
【发布时间】:2020-05-17 23:01:59
【问题描述】:

我想删除与正则表达式匹配的所有字段,同时保留所有其他字段和 JSON 的结构。 例如,假设 JSON 如下所示。

{
  "this": {
    "foobar": {
      "that": "too"
    },
    "baz": 3,
    "foo": 1
    "morefoo": {
      "foosball": "hi"
    }
  }
}

那么期望的输出将是

{
  "this": {
    "baz": 3,
    "morefoo": {}
  }
}

可以通过明确命名此处讨论的字段来干净地做到这一点:

Delete objects and arrays with jq which match a key

jq 'del(.. | .foo?, .foobar?, .foosball?)'

但我想用正则表达式来做到这一点,比如

jq 'del(.. | .("^foo")?)'  # This does not work

建议?如果可能的话,我宁愿避免with_entries,但如果这是唯一的方法,那就这样吧。

【问题讨论】:

    标签: json regex key jq


    【解决方案1】:

    这是一个使用walk的简单解决方案:

    walk(if type=="object"
         then with_entries(select(.key | test("^foo") | not))
         else . end)
    

    【讨论】:

    • 有没有办法通过递归下降来做到这一点?
    • 如果你想制作录音。描述明确的,你可以写:def d: if type=="object" then with_entries( select(.key | test("^foo") | not) | (.value|=d)) elif type == "array" then map(d) else . end; d
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 2022-10-01
    • 2010-09-09
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多