如何在JMeter脚本中使用Groovy从List中仅提取值(排除键)
在JMeter的Groovy脚本中提取Map值的几种方法
嘿,这个需求其实很容易实现,Groovy对Map的操作非常灵活,咱们结合你的场景来拆解:
你的变量a是一个包含单个Map的List,首先得先拿到这个Map对象,然后再提取里面的值。下面给你几种实用的方法:
方法1:直接按已知键提取单个值
如果你明确知道Map里的键(比如Zip和CountryID),这是最直接的方式,用Groovy的点语法就能快速取值:
def a = [{Zip=36448, CountryID=2}] // 获取List中的第一个(也是唯一的)Map def targetMap = a[0] // 提取单个值 def zipValue = targetMap.Zip def countryIdValue = targetMap.CountryID // 可以把值存到JMeter变量里,方便后续使用 vars.put("zip", zipValue.toString()) vars.put("countryId", countryIdValue.toString())
方法2:一次性获取所有值的集合
如果你不需要关心键,只想拿到所有值的集合,可以用Map的values()方法:
def a = [{Zip=36448, CountryID=2}] def targetMap = a[0] // 获取所有值,转成List方便操作 def allValues = targetMap.values().toList() log.info("提取到的所有值:${allValues}") // 输出 [36448, 2] // 如果要分别取第一个和第二个值 def zip = allValues[0] def countryId = allValues[1]
方法3:按指定顺序构建值列表
如果你想把提取的值按固定顺序整理成一个新List,直接手动构建即可:
def a = [{Zip=36448, CountryID=2}] def targetMap = a[0] def orderedValues = [targetMap.Zip, targetMap.CountryID] log.info("有序值列表:${orderedValues}") // 输出 [36448, 2]
额外场景:如果List包含多个Map
要是你的List里有多个Map对象,还可以用collect遍历提取所有值:
def a = [{Zip=36448, CountryID=2}, {Zip=12345, CountryID=3}] // 提取每个Map的Zip和CountryID,合并成一个大List def allValues = a.collect { map -> [map.Zip, map.CountryID] }.flatten() log.info("所有Map的值:${allValues}") // 输出 [36448, 2, 12345, 3]
内容的提问来源于stack exchange,提问作者Arun
相关产品推荐
相关产品推荐

