首页 > 解决方案 > Jmeter Groovy如何用{替换这个字符串

问题描述

在带有 JSR223 Groovy 的 Jmeter 中。我花了很多时间尝试在 JSON 块中替换这个字符串

"ABC": {"seconds": 20}, 

"ABC": {"seconds": ${myVal}}, (this way my value in seconds is variable)

我努力了

str1 = str1.replaceAll('"ABC": {"seconds": 20}', '"ABC": {"seconds": '+${myVal}+'"}"');

但它不会工作。请帮忙,

标签: groovyjmeter

解决方案


考虑:

def s = '''
{"ABC": {"seconds": 20}, 
 "DEF": {"seconds": 30}, 
 "IJK": {"seconds": 40}} 
'''

def myVal = 88
def oldRegex = /"ABC": \{"seconds": 20\}/
def newStr = '"ABC": {"seconds": ' + myVal + '}'
def s2 = s.replaceAll(oldRegex, newStr);

println s2

注意第一个参数replaceAll是一个正则表达式,这意味着{并且}必须被转义。在 Groovy 中转义字符时,我们通常更喜欢/\{/(a slashy-string) 而不是"\\{".


推荐阅读