首页 > 解决方案 > Gatling:将 Json 响应中的字段映射到映射对象

问题描述

我的回复看起来像这样

{
   "data":[
      {
         "id":"919274ee42fe01d40f89f51239009a2b",
         "descriptor":"Long Count_copy_1938",
         "alias":"longCount_Copy_1938",
         "type":"Numeric"
      },
      {
         "id":"435274ee42fe01d40f89f51239009a2b",
         "descriptor":"Long Count2",
         "alias":"longCount_Copy2",
         "type":"Numeric"
      },
      {
         "id":"345274ee42fe01d40f89f51239009a2b",
         "descriptor":"Short Count2",
         "alias":"Short count",
         "type":"Numeric"
      }
   ]
}

我想将“描述符”:“id”提取到地图中。映射后, Map 对象应如下所示

"Long Count_copy_1938" -> "919274ee42fe01d40f89f51239009a2b"
"Long Count2" -> "435274ee42fe01d40f89f51239009a2b"
"Short Count2" -> "345274ee42fe01d40f89f51239009a2b"

这是我实现它的方法,让我知道是否有更好的方法。谢谢!

exec(http("Get Field ids")
  .get(s"${wqlDataSources}/")
  .check(status.is(200),
  jsonPath("$.data[*].descriptor").findAll.saveAs("descriptors"),
  jsonPath("$.data[*].id").findAll.saveAs("ids")))
.exec(session => {
  val descriptors = session("descriptors").as[Vector[String]]
  val ids = session("ids").as[Vector[String]]
  val fieldIdMap = (descriptors zip ids).toMap
  session.set("fieldIdResultMap", fieldIdMap)
  session.remove("descriptors").remove("ids")
})

标签: gatlingjsonpath

解决方案


大多数 JSONPath 实现支持使用[,]联合运算符一次性提取多个值,例如$..['id','descriptor']匹配您的两个属性。
(但是,联合的可用性和结果既不通用也不一致,如果您在此处通过切换到 Goessner 或 Jayway 在线查看上述路径,您会发现结果不一样,测试站点上的 Gatling 选项卡甚至会抛出一个错误;如果该站点使用最新版本,我不知道它是否会起作用。)

我找不到任何确认 Gatling 支持工会的文档,但我在 Gatling 的 Github 存储库上发现了这个有工会的测试JsonPath.query("$.menu['file','year']", json) ...:所以,一般来说,工会应该有效。

经过反复试验,我发现这条路径可以使用 Gatling(即使是旧版本):

$.data[*]['id','descriptor']

返回:

[
   "919274ee42fe01d40f89f51239009a2b",
   "Long Count_copy_1938",
   "435274ee42fe01d40f89f51239009a2b",
   "Long Count2",
   "345274ee42fe01d40f89f51239009a2b",
   "Short Count2"
]

因此,您应该能够使用此路径一次性映射键/值对!


推荐阅读