0

I have a nested json structure and a list of json paths. I want to extract and return only those parts of json that are defined in the json paths.

For eg: Let's say the json contains:

{
    "id": 1,
    "user": {
        "name": "ABCD",
        "email": "abcd@email.com",
        "phone": "1234"
    }
}

And I've the following JsonPath's

$.id
$.user.name
$.user.phone

So the json returned will be

{
    "id": 1,
    "user": {
        "name": "ABCD",
        "phone": "1234"
    }
}

I've tried multiple ways with Jayway's JsonPath but I only get the value, not the entire heirarchy(Eg: If I search for $.user.name then I get ABCD instead of {"user": {"name": "ABCD"}}).

I looked at Extracting a subset of attributes with JSONPath but it does not answer the question of return entire json structure.

Any ideas how do I approach this? I suspect that I would need to build Jackson JsonNode iteratively using the JsonPath, but couldn't build a solution.

Note: The example above contains a simple json structure. In reality, I suspect to have many nested structures(even arrays) inside json.

JavaLearner
  • 527
  • 1
  • 5
  • 16
  • This is a duplicate of https://stackoverflow.com/q/68436665/878701. please see my answer there. – gregsdennis Jul 25 '21 at 19:39
  • @gregsdennis I do not like introducing a completely new dependency for this very specific problem. I'm looking for some easy way to do it with jackson, gson and/or jsonpath. – JavaLearner Jul 31 '21 at 16:40
  • JSON Path isn't the tool you need. It's for querying. It doesn't do transformation. That was the point of marking this as a duplicate. I don't know about those other ones you mention. – gregsdennis Aug 01 '21 at 03:24

0 Answers0