如何在Gatling/Scala中过滤API响应条目列表用于请求体?
解决Gatling中筛选API响应条目并传递的问题
最优方案:提取+内存过滤(高效简洁)
不用逐个存储条目或手动拼接字符串,直接利用Gatling的会话存储结合Scala集合操作就能完成需求,步骤如下:
- 提取整个
entry列表到会话 - 在内存中过滤掉
resourceType为"Dispense"的条目 - 将处理后的列表存回会话,供后续请求使用
完整代码示例
import io.gatling.core.Predef._ import io.gatling.http.Predef._ val scn = scenario("getAndSendInformation") .exec(http("getInformation") .post("/Information/${getInformation}") .body(ElFileBody("bodies/getInformation.json")) // 提取整个entry列表,存入会话 .check(jsonPath("$.parameter[0].entry").saveAs("entryList")) ) // 过滤处理entry列表 .exec(session => { // 将会话中的entryList转为Scala集合 val originalEntries = session("entryList").as[List[Map[String, Any]]] // 过滤掉resourceType为Dispense的条目 val filteredEntries = originalEntries.filter { entry => val resource = entry.getOrElse("resource", Map.empty[String, Any]).asInstanceOf[Map[String, Any]] resource.getOrElse("resourceType", "") != "Dispense" } // 将过滤后的列表存回会话 session.set("filteredEntryList", filteredEntries) }) .exec(http("sendInformation") .post("/Information/${sendInformation}") // 在请求模板中直接引用过滤后的列表,模板内用${filteredEntryList}即可 .body(ElFileBody("bodies/sendInformationRequest.json")) // 若无需模板,可直接构造请求体: // .body(StringBody("""{"processedEntries": ${filteredEntryList}}""")) )
关键细节说明
- 类型转换:Gatling会话中存储的
entryList本质是Scala集合,直接用.as[List[Map[String, Any]]]转换即可,无需纠结SessionAttribute类型 - 空值安全:用
getOrElse处理可能的空字段,避免测试过程中抛出异常 - 模板兼容:如果
sendInformationRequest.json需要插入处理后的列表,直接在模板对应位置写${filteredEntryList},Gatling会自动将Scala序列转为JSON数组
极简替代方案:直接用jsonPath过滤
如果不需要保留原始entry列表,可以一步到位用jsonPath的过滤语法提取符合条件的条目:
.check(jsonPath("$.parameter[0].entry[?(@.resource.resourceType != 'Dispense')]").saveAs("filteredEntryList"))
这种方式省去了额外的exec处理块,适合简单的过滤场景。
内容的提问来源于stack exchange,提问作者urdshals
相关产品推荐
相关产品推荐

