You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Gatling/Scala中过滤API响应条目列表用于请求体?

解决Gatling中筛选API响应条目并传递的问题

最优方案:提取+内存过滤(高效简洁)

不用逐个存储条目或手动拼接字符串,直接利用Gatling的会话存储结合Scala集合操作就能完成需求,步骤如下:

  1. 提取整个entry列表到会话
  2. 在内存中过滤掉resourceType为"Dispense"的条目
  3. 将处理后的列表存回会话,供后续请求使用

完整代码示例

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 17:15:14