JQ删除属性基于其他属性的值

JQ delete property based other property value

我正在尝试编写一个 JQ 过滤器,允许我根据其他值选择性地过滤对象属性。

例如,给定以下输入

{
"object1": {
"Type": "Type1",
"Properties": {
  "Property1": "blablabla",
  "Property2": [
    {
      "Key": "Name",
      "Value": "xxx"
    },
    {
      "Key": "Surname",
      "Value": "yyy"
    }
  ],
  "Property3": "xxx"
 }
},
"object2": {
"Type": "Type2",
"Properties": {
  "Property1": "blablabla",
  "Property2": [
    {
      "Key": "Name",
      "Value": "xxx"
    },
    {
      "Key": "Surname",
      "Value": "yyy"
    }
  ],
  "Property3": "xxx"
  }
 }
}

我想构建一个过滤器,它基于对象类型,例如 "Type2",删除或清除该对象的 属性,例如 Property2。 结果输出将是:

{
"object1": {
"Type": "Type1",
"Properties": {
  "Property1": "blablabla",
  "Property2": [
    {
      "Key": "Name",
      "Value": "xxx"
    },
    {
      "Key": "Surname",
      "Value": "yyy"
    }
  ],
  "Property3": "xxx"
 }
},
"object2": {
"Type": "Type2",
"Properties": {
  "Property1": "blablabla",
  "Property3": "xxx"
  }
 }
}

非常感谢任何帮助。提前致谢。

很简单。找到您要更新的对象,然后更新它们。

查看您的根对象的值,根据您的条件过滤它们,更新 Properties 属性 删除您想要的 属性。

(.[] | select(.Type == "Type2")).Properties |= del(.Property2)

对对象使用 .[] 会产生对象的所有 属性 值。另外值得一提的是,当您使用赋值更新值时,表达式的结果只是 returns 输入(换句话说,它不会更改上下文)。

直接方法:

.[] |= (if .Type == "Type2" then delpaths([["Properties", "Property2"]]) else . end)