Reputation: 23
I'm trying to write a JQ filter allowing me to selectively filter object properties based on other of it's values.
For example, given following input
{
"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"
}
}
}
I would like to construct a filter, that based upon the object type, say "Type2", deletes or clears a property of that object, say Property2. The resulting output would then be:
{
"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"
}
}
}
Any help greatly appreciated. Thanks in advance.
Upvotes: 0
Views: 2573
Reputation: 121
Another approach:
del(.[] | select(.Type == "Type2").Properties.Property2)
Upvotes: 0
Reputation: 116880
A direct approach:
.[] |= (if .Type == "Type2" then delpaths([["Properties", "Property2"]]) else . end)
Upvotes: 1
Reputation: 134521
Pretty simple. Find the objects that you want to update, then update them.
Look through the values of your root object, filtering them based on your condition, the update the Properties
property deleting the property you want.
(.[] | select(.Type == "Type2")).Properties |= del(.Property2)
Using .[]
on an object yields all property values of an object. Also worth mentioning, when you update a value using assignments, the result of the expression just returns the input (in other words, it doesn't change the context).
Upvotes: 6