繁体   English   中英

如何使用Groovy从soapui Json Response构造JsonPath?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM