0

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 and c) 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.

dcolazin
  • 831
  • 1
  • 10
  • 25

1 Answers1

1

You may try another JSON library Josson using query expression with function map().

https://github.com/octomix/josson

Josson josson = Josson.fromJsonString(
    "{" +
    "    \"a\": {\"a1\": 1, \"a2\": 2}," +
    "    \"b\": \"foo\"," +
    "    \"c\": []" +
    "}");
JsonNode node = josson.getNode("map(a.map(a2), c)");
System.out.println(node.toPrettyString());

Output

{
  "a" : {
    "a2" : 2
  },
  "c" : [ ]
}

You can compare the structure of the JSON output with this re-formatted query expression:

map(
  a.map(
    a2
  ),
  c
)
Raymond Choi
  • 1,065
  • 2
  • 7
  • 8
  • Josson looks exactly what I need. The issue now is to convert jsonpath to josson notation. I will play around a bit, thank you. – dcolazin Jun 27 '23 at 07:16