JQ 根据其他属性值删除属性

问题描述 投票:0回答:3

我正在尝试编写一个 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"
  }
 }
}

非常感谢任何帮助。预先感谢。

json jq
3个回答
6
投票

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

查看根对象的值,根据您的条件过滤它们,更新

Properties
属性删除您想要的属性。

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

在对象上使用

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


1
投票

直接方法:

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

0
投票

现在可以通过以下方式轻松完成:

del(.object2.Properties.Property2)
© www.soinside.com 2019 - 2024. All rights reserved.