You can do quite a lot with JSON-Path, it’s not limited to statically defined paths like $foo.bar
. The filtering functionality makes it possible to quite a lot of stuff dynamically.
That being said, it sounds like you need to be able to recursively remove objects that become empty as their descendants are removed. That kind of a task is out-of-scope for JSON-Path since it works on the full object tree at once. I think you can do what you want in the expression language, though. Since recursion is required, you’ll want to use an expression library to do the job. I’ll attach a library that contains a cleanupTree
function that should do what you want. The function takes a value and, if it’s an object, calls itself for each field in the object and then filters out any fields that are empty objects. In other words, it will descend to the leaves of the object hierarchy, remove any fields that have empty objects and, if that empties out an object, that field will be removed.
I’ll paste the library code in here since it’s pretty small:
{
// Returns true if the value is not an object or the object has fields.
isNotEmpty: val => !(val instanceof Object) || !val.isEmpty(),
// Recursively removes empty fields in an object.
cleanupTree: root =>
(root instanceof Object ?
root.mapValues(this.cleanupTree).filter(this.isNotEmpty) :
(root instanceof Array ?
root.map(this.cleanupTree).filter(this.isNotEmpty) : root))
}
You’ll want to unzip the attachment on your computer and then import it into your pipeline via the Pipeline Properties dialog. You can then call the function in a Mapper using lib.objutil.cleanupTree($)
.
objutil.expr.zip (325 Bytes)