Jmeter Groovy我如何用{替换此字符串 [英] Jmeter Groovy how can I replace this string with {

查看:604
本文介绍了Jmeter Groovy我如何用{替换此字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用JSR223 Groovy的Jmeter中..我花了很多时间尝试在JSON块中替换此字符串

In Jmeter with JSR223 Groovy .. I have spent a lot of time trying to replace this string in a JSON block

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

使用

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

我尝试过

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

但是它行不通.请帮助

推荐答案

使用正则表达式替换JSON中的值不是最好的主意,因为它非常脆弱,任何多余的空格或换行符都会破坏您的测试.

Replacing values in JSON using regular expressions is not the best idea as it will be very fragile and any extra space or line break will ruin your test.

我建议您使用 JsonSlurper JsonBuilder 类组合代替.此外,不要将JMeter变量称为${myVal},更好的选择是vars.get('myVal').

I would recommend going for JsonSlurper and JsonBuilder classes combination instead. Moreover, don't refer JMeter Variables as ${myVal}, a way better option would be vars.get('myVal').

完整的示例代码,以防万一:

Full example code just in case:

vars.put('myVal', '1234')

def foo = '{\n' +
        '  "ABC": {\n' +
        '    "seconds": 20\n' +
        '  }\n' +
        '}'

def json = new groovy.json.JsonSlurper().parseText(foo)
json.ABC.seconds = vars.get('myVal') as int
log.info(new groovy.json.JsonBuilder(json).toPrettyString())

演示:

更多信息:

  • Groovy: Parsing and Producing JSON
  • Apache Groovy - Why and How You Should Use It

这篇关于Jmeter Groovy我如何用{替换此字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆