加特林Gatling:将Json Response中的字段映射到Map对象

问题描述

我的回复看起来像这样

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

我想将“ descriptor”:“ 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")
})

解决方法

大多数JSONPath实现都支持使用[,]联合运算符一次性提取多个值,例如$..['id','descriptor']以匹配您的两个属性。
(但是,联合的可用性和结果既不是通用的也不是一致的,如果通过切换到Goessner或Jayway来检查上述路径online here,您会发现结果不一样,请使用Gattling选项卡在测试站点上甚至会抛出错误;如果站点使用最新版本,我无法确定它是否可行。)

我找不到任何可以证明加特林支持工会的文档,但是我在加特林的Github存储库中发现有工会的this testJsonPath.query("$.menu['file','year']",json) ...因此,总的来说工会应该可以工作。

经过反复试验,我发现此路径可用于加特林(即使是较旧版本):

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

哪个返回:

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

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

,

这里还有1个可行的解决方案,

exec(http("Get Field ids for the data source")
  .get(s"${wqlDataSources}/" + "${datasourceId}/fields)
  .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 currentFieldIdMap = (descriptors zip ids).toMap
})