JQ删除多个属性

JQ delete multiple properties

我有一个这样的对象:

{
    "a" : 1,
    "b" : {
        "c" : {
            "c1" : "abc",
            "source" : "abcxyz"
        },
        "d" : {
            "d1" : "abcd",
            "source" : "abcxyz"
        },
        "e" : {
            "e1" : "abcde",
            "source" : "abcxyz"
        }
    }
}

我的期望是

{
    "a" : 1,
    "b" : {
        "c" : {
            "c1" : "abc"
        },
        "d" : {
            "d1" : "abcd"
        },
        "e" : {
            "e1" : "abcde"
        }
    }
}

我想删除 "source" 属性。我如何在不指定键 "c"、"d" 或 "e" 的情况下执行此操作,因为它们是动态的。

可能在 jq 的下一个版本中您可以使用内置函数 walk/1。 但是目前的jq-1.5没有walk/1所以你必须从buitin.jq复制它 https://github.com/stedolan/jq/blob/master/src/builtin.jq

将以下代码保存为hoo.jq

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;

walk(if type == "object" then del(.source) else . end)

运行

$ jq -f hoo.jq < YOUR_JSON.json

参考:

遍历 .b 中的所有元素,然后将它们的值设置为从中删除 .source 元素的结果:

.b[] |= del(.source)

这是另一个解决方案

del( .b[].source )