通过循环生成JSON正文

问题描述

我正在尝试通过循环生成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,{"timestamp":1597142639469,{"timestamp":1597142639470,{"timestamp":1597142639471,"value": 100}]

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

如果有人可以帮助我,真的很感激。

谢谢。

解决方法

这与jmeter并没有真正的关系,更多的是一个古怪的问题。无论如何:

firstTimestamp = new JsonSlurper().parseText(outList.first()).'timestamp'
lastTimestamp = new JsonSlurper().parseText(outList.last()).'timestamp'
,
  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}")
}

演示:

enter image description here

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