usr4896260
usr4896260

Reputation: 1507

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.

Upvotes: 0

Views: 6542

Answers (3)

usr4896260
usr4896260

Reputation: 1507

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")

Upvotes: 0

Rao
Rao

Reputation: 21359

How about the following? And it is trivial, I guess.

Loans is a list where you get multiple Applications. Just pass the index of the Applications.

def json = new groovy.json.JsonSlurper().parseText(jsonString)
//Closure to get the particular Loan
def getLoanAt = { json.Loans[it]}
//Call above closure as method to print the 2nd Applications
​println getLoanAt(1)​

In case if you want to print all loan applications, here you do not need closure at all:

json.Loans.each {println it}​

Here is online demo for quick test.

In case, if you want a loan application by Id, use below:

//To get all loan application by Id
def getApplicationById = {id -> json.Loans.Applications.flatten().find{id == it.id}}
println getApplicationById(3)

Quick demo of the above.

Upvotes: 2

QuakeCore
QuakeCore

Reputation: 1926

You can try to convert your json to java object Map to be accurate, after that you can get the Loans as an object ArrayList.

def myJson = new JsonSlurper().parseText("{\"Errors\": [], \"Loans\": [{\"id\": 1}, {\"id\": 2}]}");
def loansList = myJson.Loans// ArrayList

Upvotes: 1

Related Questions