【问题标题】:Generate a JSON body by looping通过循环生成 JSON 正文
【发布时间】:2020-12-01 00:56:04
【问题描述】:

我正在尝试通过循环生成 JSON 请求正文。我正在为此使用 groovy,因为这是 JMeter 的工作。

这是我到目前为止所做的。

def outList = [];
for (i = 0; i < ${noDataPoints}; i++) {    
Date latestdate = new Date(); 
outList.add("{\"timestamp\":" + latestdate.getTime() + ",\"value\": 100}")
sleep 1
}

在这里,当我将值传递给 noDataPoints 时,它会给出以下输出。

[{"timestamp":1597142639466,"value": 100}, {"timestamp":1597142639467,"value": 100}, {"timestamp":1597142639469,"value": 100}, {"timestamp":1597142639470,"value": 100}, {"timestamp":1597142639471,"value": 100}]

现在我要做的是,我想将上面列表的1st timestamp和上面列表的last timestamp保存到2 variables中以供进一步计算。

如果有人能帮我解决这个问题,我真的很感激。

提前致谢。

【问题讨论】:

    标签: json list loops groovy jmeter


    【解决方案1】:

    这实际上与 jmeter 无关,它更像是一个 groovy 问题。无论如何:

    firstTimestamp = new JsonSlurper().parseText(outList.first()).'timestamp'
    lastTimestamp = new JsonSlurper().parseText(outList.last()).'timestamp'
    

    【讨论】:

      【解决方案2】:
      1. 不要将 JMeter 函数或变量内联到 Groovy 脚本中:

      2. 使用Thread.sleep() is a some form of a performance antipattern,请考虑增加值。

      3. 您有计数器,因此您可以使用上述 vars 速记法将第一个和最后一个值存储到 JMeter 变量中

      建议修改代码:

      def outList = [];
      def noDataPoints = vars.get('noDataPoints') as int
      def latestdate = new Date().getTime()
      for (i = 0; i < noDataPoints; i++) {
          latestdate++
          if (i == 0) {
              vars.put('1sttimestamp', latestdate as String)
          }
          if (i == noDataPoints - 1) {
              vars.put('lasttimestamp', latestdate as String)
          }
          outList.add("{\"timestamp\":" + latestdate + ",\"value\": 100}")
      }
      

      演示:

      更多信息:Top 8 JMeter Java Classes You Should Be Using with Groovy

      【讨论】:

        猜你喜欢
        • 2016-04-26
        • 1970-01-01
        • 2020-10-10
        • 2012-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-09
        相关资源
        最近更新 更多