import com.jayway.jsonpath.JsonPath
def pathToRead = someFilePath;
def pathToWrite = someOtherFilePath;
def newLine = System.getProperty('line.separator')
def index = [];
def randoms = [];
def temp;
//generating random numbers
def size = new File(pathToRead + "index.csv").readLines().size();
for(int i=0; i<vars.get('extractCount'); i++)
{
randoms << org.apache.commons.lang3.RandomUtils.nextInt(0, size-1);
}
//Reading file names to extract data
File file = new File(pathToRead + "index.csv");
file.each { line ->
index << line
}
def nameCSV = new File(pathToWrite + 'name.csv')
def nameGivenCSV = new File(pathToWrite + 'given.csv')
def givenList = []
def nameFamilyCSV = new File(pathToWrite + 'family.csv')
def familyList = []
//going through each json file and extracting data and storing in lists
randoms.unique().each { random ->
jsonString = new groovy.json.JsonSlurper().parseText(new File(pathToRead + "Data/fhir/" + index.getAt(random)).text);
def names = JsonPath.read(jsonString, '$..name')
names.each { name ->
name.each { subName ->
subName.get('given').each { givenName ->
if(givenName != null)
givenList << givenName
}
temp = subName.get('family')
if(temp != null)
familyList << temp
}
}
}
//Writing data to files after removing the duplicates
givenList.unique().each { single_given ->
nameCSV << single_given << newLine
nameGivenCSV << single_given << newLine
}
familyList.unique().each { single_family ->
nameCSV << single_family << newLine
nameFamilyCSV << single_family << newLine
}
这是错误提示 JSR223脚本ExtractRandomData中的问题,消息:javax.script.ScriptException:groovy.lang.MissingMethodException:方法的无签名:java.lang.String.get()适用于参数类型:(java.lang.String)值:[给定]
这意味着它不允许我应用subName.get('given');
文件中的json数据就像
"name": [
{
"use": "official",
"family": "Cortez851",
"given": [
"Benito209"
],
"prefix": [
"Mr."
]
}
]
答案 0 :(得分:0)
您的代码与您提供的JSON数据匹配,并且应该可以正常工作。但是,如果要查看错误,则某些文件的结构会有所不同。
您可以通过使用instanceof运算符显式检查您正在使用的subname
的类型来解决此问题,例如:
names.each { name ->
name.each { subName ->
if (subName instanceof Map) {
subName.get('given').each { givenName ->
if (givenName != null)
givenList << givenName
}
} else if (subName instanceof String) {
givenList << subName
} else {
log.error('Expected Map or String, got' + subName.getClass().getName())
}
temp = subName.get('family')
if (temp != null)
familyList << temp
}
}
演示:
其他改进:
您似乎根本没有使用JsonSlurper,因此可以简化此行:
jsonString = new groovy.json.JsonSlurper().parseText(new File(pathToRead + "Data/fhir/" + index.getAt(random)).text);
对此 jsonString = new File(pathToRead +“ Data / fhir /” + index.getAt(random))。text
此行将永远不会访问index.csv
randoms << org.apache.commons.lang3.RandomUtils.nextInt(0, size-1);
您应该将其更改为
randoms << org.apache.commons.lang3.RandomUtils.nextInt(0, size);
您可以将代码放在全局try block中,并在出现故障时将有问题的JSON打印到 jmeter.log 文件中
更多信息: