1

I have a JSON response which I was able to filter to a format like the one below using jayway jsonpath syntax:

[
   {
      "entityName" : "Financial Assets",
      "entityFullPath" : [
         "Path123",
         "Alternative"
      ]
   },
   {
      "entityName" : "123",
      "entityFullPath" : [
         "Path123",
         "Alternative"
      ]
   }
]

jsonpath:

$..domainEntity[?(@.dataObjectId !== null)].['entityName','entityFullPath']

What I want to do further, is to get only the first value from entityFullPath array - is that case Path123, so the final JSON would look like this:

[
   {
      "entityName" : "Financial Assets",
      "entityFullPath" : [
         "Path123"
      ]
   },
   {
      "entityName" : "123",
      "entityFullPath" : [
         "Path123"
      ]
   }
]

Or even better (not sure if you can get rid of json array like that using only jsonpath):

[
   {
      "entityName" : "Financial Assets",
      "entityFullPath" : "Path123"
   },
   {
      "entityName" : "123",
      "entityFullPath" : "Path123"
     
   }
]

Is such drill down doable using only jsonpath? I'm using jayway flavor.

1 Answer 1

1

Unfortunately, this is not possible. Unlike XPath, JSONPath (as of now) offers no operations for accessing parent or sibling nodes from the given node. Furthermore, the [,] union operation (as commonly implemented) does not allow us to join nodes on different levels; that's why we are stuck here.

A not so elegant workaround that comes to mind is recreating the target JSON by merging the result of two (or more) individual JSONPath queries. Here is a JavaScript example of how this could look like:

let json = [
   {
      "entityName" : "Financial Assets",
      "entityFullPath" : [
         "Path123",
         "Alternative"
      ]
   },
   {
      "entityName" : "123",
      "entityFullPath" : [
         "Path123",
         "Alternative"
      ]
   }
];

var a = JSONPath.JSONPath({path: '$.[*].entityName', json: json});
//= [
//   "Financial Assets",
//   "123"
//];
var b = JSONPath.JSONPath({path: '$.[*].entityFullPath.[0]', json: json});
//= [
//   "Path123",
//   "Path123"
//];
const result = Object.assign({}, [{"entityName":a[0], "extern_uid":b[0]},
                                  {"entityName":a[1], "extern_uid":b[1]}]);
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/index-umd.min.js"></script>

It's arguably best to work with the previous result and access the properties as needed in your regular code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.