Obeth Samuel
Obeth Samuel

Reputation: 610

How to got nth position value from integer array in JsonPath Finder?

I'm trying to get nth position value from an integer array. My Input JSON :

{
 "data" : [
     {
        "status" : "ACTIVE" ,
       "id" : 1 ,
        "isEnabled" : true,
        "sample" : [ 1,  2, 3,  4 ]
     } ,
     {
        "status" : "DEACTIVATE" ,
       "id" : 2 ,
        "isEnabled" : false,
        "sample" : [ 1,  2, 3 ]
     } ,
     {
        "status" : "ACTIVE" ,
       "id" : 3 ,
        "isEnabled" : false ,
        "sample" : [ 1,  2 ]
     },
     {
        "status" : "DEACTIVATE" ,
        "id" : 4 ,
        "isEnabled" : true ,
        "sample" : [ 1 ]
     }
 ]
}

My input JsonPath :

$.data[?((@.status != null) && (@.isEnabled == true))].sample[0]

Expected output: [1,2,3,4]

But got: [1,1]

So how do I get my expected value in jsonpath? I am using this tool.

Upvotes: 0

Views: 567

Answers (1)

user3942918
user3942918

Reputation: 26413

I believe with jsonpath you'd need to use two expressions. Remove the trailing [0] from what you've got (it's currently selecting the first element of each sample rather than the first group of your filtered result set), giving you:

$.data[?((@.status != null) && (@.isEnabled == true))].sample

then take the evaluated result:

[[1,2,3,4],[1]]

and run it through $[0] to retrieve the first group from the set. In the end leaving you with:

[1,2,3,4]

I'm not sure if there's supposed to be a way to do what you're doing in jsonpath with a single expression - it's a pretty poorly specified language.


In jmespath you could do basically the same thing, but pipe them together to achieve the result in one shot, e.g.:

data[?status != null && isEnabled].sample | [0]

in case that's a preferable option for you.

Upvotes: 2

Related Questions