我有一个包含以下内容的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

最佳答案

您的问题是type == "array"为true时.将是一个数组,因此.userGroupAccesses无法正常工作。您想要做的只是关注.是一个对象的情况。在调用walk时,您只需要检查type == "object",然后删除不需要的成员即可。例如

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

Try it online at jqplay.org

您也可以使用Recursive Descent walk 来解决此问题,而无需使用..
del(.. | .publicAccess?, .userGroupAccesses?)

Try it online at jqplay.org

关于arrays - 用jq删除与键匹配的对象和数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47371280/

10-11 06:53