Home > OS >  Create path to get a specific object from an array
Create path to get a specific object from an array

Time:10-07

I want to get the values from a JSON highlighted in the image. Can anyone help me, how can I build a path to get these values. With the code I have it returns me all the id, but I only need a second object that is in the array. For more details I have left an example in the image.

JSON Structure

I'm using Restassured to do it.

public static List<String>  JSON_UltimateParent(String parent) { 
        baseURI = uri;
        List<List<String>>  LinkedListUltimate = 
                    given() 
                        .auth().basic(getJiraUser(), getJiraPass())
                        .param("limit", "74000000")
                        .param("count", "false")
                        .param("sort", "accountId")
                    .when()
                        .get("/counterparties.json?"  parent)
                    .then() 
                        .extract().path("riskUltimateParent.identifier.id"); 

        List<String> ultimates = linkedList_To_List(LinkedListUltimate);
                    
        return ultimates;
    }

This method make the parse to list

public static List<String> linkedList_To_List(List<List<String>> response){
        List<String> accountIds = response.stream().flatMap(l-> l.stream()).collect(Collectors.toList());
        return accountIds;
    }

CodePudding user response:

The JSON shared in the screenshot should be valid. Below is the valid version:

{
"riskUltimateParent" : 
[{
    "name": "Test1",
    "identifier" : [{"id":1,"type":"abcd1"},{"id":2,"type":"abcd2"},{"id":3,"type":"abcd3"}]
},
{
    "name": "Test2",
    "identifier" : [{"id":4,"type":"abcd4"},{"id":4,"type":"abcd5"},{"id":6,"type":"abcd6"}]
}]
}

The JSON path that you are looking for should be extract().path("riskUltimateParent[:].identifier[1]");

If you need id or type:

extract().path("riskUltimateParent[:].identifier[1].id");  
extract().path("riskUltimateParent[:].identifier[1].type"); 

CodePudding user response:

I use jsonpath jayway, this is the sample code:

String res = given()...asString();
List<String> ids = JsonPath.read(res, "$..identifier[?(@.type == 'CLIENTREF')].id");
System.out.println(ids);
//["AVIVANVS","DAVIDSNKC"]

pom.xml

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.6.0</version>
</dependency>
  • Related