[英]How to construct the JsonPath from soapui Json Response using groovy?
我有如下所示的soapui響應,我試圖解析相同的內容並打印json響應中的所有元素(來自葉節點)。
樣本Json:
{
"BookID": 7982,
"author": {
"authorname": "roboin"
},
"authorid": "X-1-23",
"BookDetails": [{
"Price": "100",
"Location": "Paris"
}],
"authordob": "1980-11-10",
"Adverts": {
"online": true
}
}
下面的groovy腳本的使用是打印響應中的所有元素。下面的代碼轉到Json響應中的每個元素,並按以下“預期結果”進行打印,
預期結果: 打印所有元素(葉節點)jsonpath和值
$。['author'] ['authorname']:機器人
$ [ 'BookDetails'] [0] [ '價格']:100
當前結果: 打印所有元素和值
作者名稱:roboin
價格:100
import groovy.json.*
//Get the test case response from context and parse it
def contextResponse = messageExchange.getResponseContent().toString()
//log.info(contextResponse)
def parseResponse = new JsonSlurper().parseText(contextResponse)
//log.info(parseResponse)
def parseMap(map) {
map.each {
if (it.value instanceof Map) {
parseMap(it.value)
} else if (it.value instanceof List) {
log.info(it.key + ": ")
parseArray(it.value)
} else {
log.info(it.key + ": " + it.value)
}
}
}
def parseArray(array) {
array.each {
if (it instanceof Map) {
parseMap(it)
} else if (it instanceof List) {
parseArray(it)
} else {
log.info("arrayValue: $it");
}
}
}
parseMap(parseResponse)
我對此進行了一些研究,發現在線沒有幾個json路徑選擇器,並且無法在我的soapui應用程序中使用。我想迭代並打印所有元素json路徑及其值。
當前,上面的代碼迭代並僅打印元素名稱和值。
def j=new groovy.json.JsonSlurper().parseText('''{
"BookID": 7982,
"author": {
"authorname": "roboin"
},
"authorid": "X-1-23",
"BookDetails": [{
"Price": "100",
"Location": "Paris"
}],
"authordob": "1980-11-10",
"Adverts": {
"online": true
}
}''')
void printJsonPaths(o, path='$'){
if(o instanceof Map){
o.each{ k,v-> printJsonPaths(v, path+"['${k}']") }
}else if(o instanceof List){
o.eachWithIndex{ v,i-> printJsonPaths(v, path+"[${i}]") }
}else{
println("${path}: ${o}")
}
}
printJsonPaths(j)
產量
$['BookID']: 7982
$['author']['authorname']: roboin
$['authorid']: X-1-23
$['BookDetails'][0]['Price']: 100
$['BookDetails'][0]['Location']: Paris
$['authordob']: 1980-11-10
$['Adverts']['online']: true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.