【问题标题】:Jmeter Groovy how can I replace this string with {Jmeter Groovy如何用{替换这个字符串
【发布时间】:2018-05-29 12:25:52
【问题描述】:

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

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

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

我试过了

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

但它不会工作。请帮忙,

【问题讨论】:

    标签: groovy jmeter


    【解决方案1】:

    考虑:

    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 中转义字符时,我们通常更喜欢 /\{/(斜线字符串)而不是 "\\{"

    【讨论】:

      【解决方案2】:

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

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

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

      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())
      

      演示:

      更多信息:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 2014-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多