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

Scala中将CSV数据转换为Map列表 适配Gatling Pebble模板需求

解决方案

首先明确Gatling读取CSV的默认返回结构:调用csv("my.csv").readRecords()会返回List[Map[String, String]],其中每个元素对应CSV的一行,key为CSV的列名(id、weight),value为对应列的字符串值。

注意:你给出的Pebble入参格式存在语法笔误,以下实现是基于修正后的Iterator[Map[String, List[Map[String, String]]]]结构适配,符合Gatling整合Pebble的传参规范。

转换代码实现

你可以参考以下Scala代码完成格式转换:

import scala.jdk.CollectionConverters._

// 读取CSV并转换字段类型,得到目标格式的Map列表
val targetRecords = csv("my.csv").readRecords()
  .map(row => Map(
    "id" -> row("id").toInt,
    "weight" -> row("weight").toInt
  ))

// 若需要按id分组,可增加以下分组逻辑
val groupedRecords = targetRecords
  .groupBy(_("id").asInstanceOf[Int])
  .toList
  .map { case (id, weightRecords) =>
    Map(
      "id" -> id,
      "weightList" -> weightRecords.map(_("weight"))
    )
  }

// 转换为Pebble兼容的Java迭代器格式
val pebbleParam = Iterator(
  Map(
    "flatRecords" -> targetRecords.asJava,
    "groupedRecords" -> groupedRecords.asJava
  )
).asJava

Pebble模板调用示例

在模板中可以直接读取对应字段使用:

<!-- 遍历单条记录,直接输出你需要的Map格式 -->
{% for record in flatRecords %}
Map("id"->{{ record.id }},"weight"->{{ record.weight }})
{% endfor %}

<!-- 遍历分组后的记录 -->
{% for group in groupedRecords %}
id为{{ group.id }}的所有weight: {{ group.weightList | join(", ") }}
{% endfor %}

如果你需要直接在Scala代码中生成示例中的Scala Map格式字符串列表,可额外增加拼接逻辑:

val mapFormatStrings = targetRecords.map(record => 
  s"""Map("id"->${record("id")},"weight"->${record("weight")})"""
)

内容的提问来源于stack exchange,提问作者surbhi khare

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 01:03:03