如何在jmeter中使用groovy脚本从csv数据集配置制作json数组 [英] How to make json array from csv data set config using groovy script in jmeter
本文介绍了如何在jmeter中使用groovy脚本从csv数据集配置制作json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含多个记录的Csv文件(以逗号分隔),我需要一个Groovy脚本,该脚本可以从csv获取所有数据,并创建一个json数组并在jmeter中发送POST请求.这是我的下面的代码.但是它只能获取一条记录
I have a Csv file with multiple records(comma Seperated), i need a groovy script that can fetch all the data's from csv and make a json array and send a POST request in jmeter. Here is my code below. But it only fetches one record
import groovy.json.*
import groovy.json.JsonBuilder
def jsonBuilder = new groovy.json.JsonBuilder()
jsonBuilder {
id Integer.parseInt(vars.get("id"))
name vars.get("first_name")
last_name vars.get("last_name")
email vars.get("email")
institute_id Integer.parseInt(vars.get("institute_id"))
category_id Integer.parseInt(vars.get("category_id"))
value Boolean.parseBoolean(vars.get("value"))
}
sampler.addNonEncodedArgument("",jsonBuilder.toPrettyString(),"")
sampler.setPostBodyRaw(true)
推荐答案
假定您具有以下CSV文件:
Assuming you have the following CSV file:
id,first_name,last_name,email,institute_id,category_id,value
1,john,doe,johndoe@example.com,1,1,true
2,jane,doe,janedoe@example.com,2,2,false
您可以使用以下Groovy代码将其转换为 JSON数组:>
You can convert it into a JSON Array using below Groovy code:
import groovy.json.JsonOutput
def lines = new File('test.csv').readLines()
def keys = lines[0].split(',')
def rows = lines[1..-1].collect { line ->
def i = 0, vals = line.split(',')
keys.inject([:]) { map, key -> map << ["$key": vals[i++]] }
}
log.info(JsonOutput.prettyPrint(JsonOutput.toJson(rows)))
演示:
参考文献:
- JsonOutput class reference
- Groovy: Parsing and Producing JSON
- Apache Groovy - Why and How You Should Use It
这篇关于如何在jmeter中使用groovy脚本从csv数据集配置制作json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文