Looping through JSON array and extract attributes

I have a block of code which needs to loop through a JSON array which is obtained from response of a REST service.

.exec(http(“Request_1”)
.post("/endPoint")
.headers(headers_1)
.body(StringBody(""“REQUEST_BODY”"")).asJSON
.check(jsonPath("$.result").is(“SUCCESS”))
.check(jsonPath("$.data[*]").findAll.saveAs(“pList”)))
.exec(session => {
println(session)
session
})
.foreach("${pList}", “player”){
exec(session => {
val playerId = JsonPath.query("$.playerId", “${player}”)
session.set(“playerId”, playerId)
})
.exec(http(“Request_1”)
.post("/endPoint")
.headers(headers_1)
.body(StringBody("""{“playerId”:"${playerId}"}""")).asJSON
.check(jsonPath("$.result").is(“SUCCESS”)))

}

The response format of the first request was

{
“result”: “SUCCESS”,
“data”: [
{
“playerId”: 2
},
{
“playerId”: 3
},
{
“playerId”: 4
}
]
}

I am seeing in the second request the body is {“playerId”:"Right(empty iterator)} Expected : 3 requests with body as {“playerId”:1} {“playerId”:2} {“playerId”:3}

SOF Crosspost

Hi Neil,

Couldn’t you just extract playerIds directly from the first jsonPath query instead of doing it manually through a foreach block ?
e.g. $.data[*].playerId then a foreach on “pList”.

Hi Pierre,

That is what I eventually did . The actual response of my first request is having more than one attribute that I have to loop through

{
“result”: “SUCCESS”,
“data”: [
{
“playerId”: 2,

“score” :100

},
{
“playerId”: 3,
“score” :200
},
{
“playerId”: 4
“score” :200"
}
]
}

i’ve used another json parser to do something similar (lift-json in my case):

.exec(http("…")
.get("…")
.headers(headers_…)
.check(bodyString.transform(extractXXX(_)).saveAs(“xxx”)))

private def extractXXX(json: String) =
(JsonParser.parse(json) \ “xxx”).values.asInstanceOf[Seq[Map[String, Any]]]

so later you can access ${xxx.whateverFieldName}

Just so that everyone knows this has been answered in SOF by Michelle
http://stackoverflow.com/a/25384387/747456

I have a similar setup wherein I am saving the multiple players. However, in case of empty result list, the request is marked as KO.

For example, if the output is

{ "result": "SUCCESS", "data": [] }

In this case, request is marked as KO below
Request: player-request: KO jsonPath($.value[*]).findAll.exists, found nothing

I understand this is because jsonpath() is inside check(). I was seeing the dontValidate in some other thread, but it doesn’t exist in current implementation.

What should I do in this case?