【问题标题】:Delete objects and arrays with jq which match a key使用 jq 删除与键匹配的对象和数组
【发布时间】:2017-11-18 21:30:41
【问题描述】:

我有一个包含以下内容的 JSON:

{
  "data": [
    {
      "name": "Test",
      "program": {
        "publicAccess": "--------",
        "externalAccess": false,
        "userGroupAccesses": [
          {
            "access": "r-------"
          },
          {
            "access": "rw------"
          }
        ],
        "id": "MmBqeMLIC2r"
      },
      "publicAccess": "rw------"
    }
  ]
}

我想删除所有匹配 publicAccessuserGroupAccesses 的键(递归),这样我的 JSON 看起来像这样:

{
  "data": [
    {
      "name": "Test",
      "program": {
        "externalAccess": false,
        "id": "MmBqeMLIC2r"
      }
    }
  ]
}

我从source 复制了jq 的内置walk 函数。

# Apply f to composite entities recursively, and to atoms
def walk(f):
  . as $in
  | if type == "object" then
      reduce keys[] as $key
        ( {}; . + { ($key):  ($in[$key] | walk(f)) } ) | f
  elif type == "array" then map( walk(f) ) | f
  else f
  end;

# My Code
walk(if (type == "object" and .publicAccess)
        then del(.publicAccess)
     elif (type == "array" and .userGroupAccesses)
        then del(.userGroupAccesses)
     else
       .
end )

给我jq: error (at <stdin>:2622): Cannot index array with string "userGroupAccesses"。另外,如果我使用.userGroupAccesses[] - 我如何获得结果?

jqplay 上的片段:https://jqplay.org/s/1m7wAeHMTu

【问题讨论】:

  • 您从旧的 builtin.jq 复制。明智的做法是使用keys_unsorted 而不是keys

标签: arrays json jq


【解决方案1】:

您的问题是当type == "array" 为真时. 将是一个数组,因此.userGroupAccesses 将不起作用。您要做的是关注. 是对象的情况。在您致电walk 时,您只需检查type == "object",然后删除您不想要的成员。例如

walk(if type == "object" then del(.publicAccess, .userGroupAccesses) else . end)

Try it online at jqplay.org

您也可以在没有walk 的情况下使用Recursive Descent .. 来解决此问题,例如

del(.. | .publicAccess?, .userGroupAccesses?)

Try it online at jqplay.org

【讨论】:

  • 感谢您提到递归下降..。我没有意识到这一点,这让我很开心。
  • 如果您只需要从数组jq '.[] | del(.THE_KEY)'中的顶级对象中删除一个键
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
  • 2018-08-14
  • 1970-01-01
  • 2017-07-26
相关资源
最近更新 更多