简体   繁体   中英

jayway jsonpath filter inner json array

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.

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/jsonpath-plus@4.0.0/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM