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

SoapUI使用Groovy脚本如何动态提取JSON响应的货币字段

Groovy JsonSlurper 动态取货币属性解决方案

问题根因

  1. 你解析后的slurperResponse是数组结构(接口响应最外层为[]),需要先取数组首个元素才能拿到国家属性对象
  2. currencies字段是Map结构而非数组,你之前通过字符串截取获取货币代码的方式不可靠,直接取Map的键集即可拿到动态货币代码
  3. 硬编码currencies.RUB.name用的是Groovy Map的固定key点语法,动态key需要用方括号语法取值

修改后可运行代码

import groovy.json.JsonSlurper

def responseContent = testRunner.testCase.getTestStepByName("CountryCode").getPropertyValue("Response")
def slurperResponse = new JsonSlurper().parseText(responseContent)

// 取第一个国家对象的货币Map
def currencyMap = slurperResponse[0].currencies
// 动态获取货币代码(单货币场景直接取第一个key,多货币可遍历)
def dynamicCurrencyCode = currencyMap.keySet().first()
// 动态传入货币代码取对应属性
def currencyName = currencyMap[dynamicCurrencyCode].name
def currencySymbol = currencyMap[dynamicCurrencyCode].symbol

// 验证输出
println "货币代码:${dynamicCurrencyCode}"
println "货币名称:${currencyName}"
println "货币符号:${currencySymbol}"

多货币场景适配

如果同一个国家返回多货币,直接遍历Map即可:

currencyMap.each { code, info ->
    println "货币代码:${code},货币名称:${info.name},货币符号:${info.symbol}"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:24:03