14

I am trying to parse a json response returned to gatling by the server.

My response from server is:

SessionAttribute(
  Session(
    GetServices,
    3491823964710285818-0,
    Map(
      gatling.http.cache.etagStore -> Map(https://api.xyz.com/services -> ), 
      gatling.http.cache.lastModifiedStore -> Map(https://api.xyz.com/services -> ),
      myresponse -> {
        "created":"2014-12-16T22:06:59.149+0000",
        "id":"x8utwb2unq8uey23vpj64t65",
        "name":"myservice",
        "updated":"2014-12-16T22:06:59.149+0000",
        "version":null
      }),
    1418767654142,622,
    OK,List(),<function1>),id)

I am doing this in my script:

val scn = scenario("GetServices")
          .exec(http("Get all Services")
          .post("/services")
          .body(StringBody("""{ "name": "myservice" }""")).asJSON
          .headers(sentHeaders)
          .check(jsonPath("$")
          .saveAs("myresponse"))
).exec(session => {
  println(session.get("id"))
  session
})

It is still printing the whole response. How can I just retrieve the id which is "x8utwb2unq8uey23vpj64t65"?

millhouse
  • 9,817
  • 4
  • 32
  • 40
user1075958
  • 201
  • 1
  • 3
  • 6

1 Answers1

27

It might be easiest to use a little bit more jsonPath to pull out the id you need, storing that in its own variable for later use. Remember that jsonPath is still a CheckBuilder, so you can't just access the result directly - it might have failed to match.

Converting it to an Option[String] seems like a reasonable thing to do though.

So your final few lines would become:

    ...
    .check(
      jsonPath("$.id").saveAs("myresponseId")
    )
  )
).exec(session => {
  val maybeId = session.get("myresponseId").asOption[String]
  println(maybeId.getOrElse("COULD NOT FIND ID"))
  session
})
millhouse
  • 9,817
  • 4
  • 32
  • 40
  • 2
    Thanks for this answer. Bit late to the game here but very helpful for those of us getting started with Gatling. – renderf0x Oct 12 '16 at 05:08
  • 1
    I spent my 2 days to find out what wrong I'm doing with regex. jsonPath solved the issue. (feeling relaxed) – Amit Kumar Gupta Feb 20 '17 at 14:34
  • 4
    Recent versions of Gatling do not have the `session.get` API. Instead, just do `session("myresponseId").asOption[String]`. – rosendin Nov 07 '18 at 21:57