我正在尝试编写一个 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)
在对象上使用
.[]
会生成对象的所有属性值。另外值得一提的是,当您使用赋值更新值时,表达式的结果仅返回输入(换句话说,它不会更改上下文)。
直接方法:
.[] |= (if .Type == "Type2" then delpaths([["Properties", "Property2"]]) else . end)
现在可以通过以下方式轻松完成:
del(.object2.Properties.Property2)