解析Json的回应回到了Gatling

时间:2022-05-14 21:30:22

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

我试图解析由服务器返回给gatling的json响应。

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"?

它仍在打印整个响应。我怎样才能检索到“x8utwb2unq8uey23vpj64t65”的id?

1 个解决方案

#1


20  

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.

最简单的方法是使用更多的jsonPath来提取你需要的id,将它存储在自己的变量*以后使用。请记住,jsonPath仍然是一个CheckBuilder,因此您不能直接访问结果 - 它可能无法匹配。

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

将它转换为Option [String]似乎是一件合理的事情。

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
})

#1


20  

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.

最简单的方法是使用更多的jsonPath来提取你需要的id,将它存储在自己的变量*以后使用。请记住,jsonPath仍然是一个CheckBuilder,因此您不能直接访问结果 - 它可能无法匹配。

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

将它转换为Option [String]似乎是一件合理的事情。

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
})