I have a list of (somehow "well-behaved") jsonpaths and I have to return an object which contains only the elements described in the list. For example, given the list ["$.a.a2", $.c]
and the object
{
"a": {"a1": 1, "a2": 2},
"b": foo,
"c": []
}
the desired result is
{
"a": {"a2": 2},
"c": []
}
I'm using Jayway Jsonpath, but I'm open to use other libraries. My current solution is the following:
- find the minimal jsonpath list that describe the same set of elements (i.e. remove
"$.a.a2"
if"$.a"
is present); - determine the leaf objects (in the first example
a2
andc
) and build a map that is capable to contain them, as creation of deep nodes is still not supported: in the first example, after this step I'm creating a map{"a": {}}
; - read the values from the initial object and copy them in the map with the provided methods
read
/set
.
I'm quite surprised that such feature is not present. Is there a better way to filter properties in an object? Squiggly might be a suitable solution, but is not maintained.