sathya
sathya

Reputation: 199

How to construct the JsonPath from soapui Json Response using groovy?

I have an soapui response like below and i tried to parse the same and print all the elements(From leaf node) in the json response.

Sample Json :

{
    "BookID": 7982,
    "author": {
        "authorname": "roboin"

    },
    "authorid": "X-1-23",
    "BookDetails": [{
        "Price": "100",
        "Location": "Paris"
    }],
    "authordob": "1980-11-10",

    "Adverts": {
        "online": true

    }
}

Use of below groovy script is to print all the elements in the response.The below code goes to each and every element in the Json response and print like below Expected Result,

Expected Result: Print all the element(leaf node) jsonpath and values

$.['author']['authorname'] : roboin

$.['BookDetails'][0]['Price']:100

Current Result : Prints all the elements and values

authorname : roboin

Price: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)

I tried some research about this and found few json path selector in online and that can't be used inside my soapui application.i want to iterate and print all the elements json path and their values.

Currently the above code iterate and prints only the element name and values.

Upvotes: 0

Views: 745

Answers (1)

daggett
daggett

Reputation: 28564

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)

output

$['BookID']: 7982
$['author']['authorname']: roboin
$['authorid']: X-1-23
$['BookDetails'][0]['Price']: 100
$['BookDetails'][0]['Location']: Paris
$['authordob']: 1980-11-10
$['Adverts']['online']: true

Upvotes: 1

Related Questions