Search code examples
javajsongroovykatalon-studiojsonslurper

Groovy get object within json slurper object with string


I'm trying create a function in which I pass a json object from JsonSlurper and a string which contains json object located in the original. If it does, it returns true or false if the elements count condition is satisfied. For example:

myJson:

{
  "Errors": [],
  "Loans": [
    {
      "Applications": [
        {
          "id": 1,
          "name": "test"
        }
      ]
    },
    {
      "Applications": [
        {
          "id": 2,
          "name": "test3"
        },
        {
          "id": 3,
          "name": "test3"
        }
      ]
    }
  ]
}

My method would get the json array as follows:

def myJson = new JsonSlurper().parseText(receivedResponse.responseBodyContent)
def result = verifyElementsCountGreaterThanEqualTo(myJson, "Loans[0].Applications[1]", 3)

Is there such a library that can do this for me?

I've tried myJson["Loans[0].Applications[1]"] to get the Json Object so I can get the size, but the result is null.


Solution

  • After a lot of searching, I was able to find a solution with the rest assured api.

    I'm able to use a string for the path I'm looking for in the Json object as follows:

    import io.restassured.path.json.JsonPath as JsonPath
    
    def myJson = "{'Errors':[],'Loans':[{'Applications':[{'id':1,'name':'test'}]},{'Applications':[{'id':2,'name':'test3'},{'id':3,'name':'test3'}]}]}"    
    def applicationData = JsonPath.with(myJson).get("Loans[0].Applications[1]")
    def applicationsListData = JsonPath.with(myJson).get("Loans[0].Applications")