1

I am trying to parse a JSON response that has repeating objects with JsonSlurper to compare to a JDBC query. However, I only want to compare objects where a certain values exist within that object.

If I had a response that looks like this, how would I only parse the objects where the country equals USA or Canada, therefore ignoring anything else?

{
    "info": [{
        "name": "John Smith",
        "phone": "2125557878",
        "country": {
            "value": "USA"
        }
    },
    {
        "name": "Jane Smith",
        "phone": "2125551212",
        "country": {
            "value": "USA"
        }
    },
    {
        "name": "Bob Jones",
        "phone": "4165558714",
        "country": {
            "value": "Canada"
        }
    },
    {
        "name": "George Tucker",
        "phone": "4454547171",
        "country": {
            "value": "UK"
        }
    },
    {
        "name": "Jean Normand",
        "phone": "4454547171",
        "country": {
            "value": "France"
        }
    }]
}

This is what I have in groovy:

def jsonResponse = context.expand('${RESTRequest#Response}')
def parsedJson = new JsonSlurper().parseText(jsonResponse)
def info = parsedJson.info

    def jsonDataObjects = []
    info.each { json ->
        jsonDataObjects.add(Model.buildJSONData(json))
    }

I am building a collection of the elements that I need to compare to a database. How do I only add to that collection where the info.country.value = USA or Canada?

I tried using .findAll like this just to test if I could get it to filter by just one of the countries:

def info = parsedJson.info.country.findAll{it.value == "USA"}

But, when I do that, only the value field is kept. I lose the name and phone from the parse.

Thanks in advance for any assistance.

JesseN
  • 47
  • 1
  • 9
  • 1
    The JSON you shown is incorrect - it duplicates `info` field multiple times, so when you parse it with JsonSlurper it looks like this `{"info":{"name":"Jean Normand","phone":"4454547171","country":{"value":"France"}}}` – Szymon Stepniak Aug 30 '18 at 18:07
  • That was my mistake from mocking data instead of copying what I was using. Info should be at the top and the rest in an array. I will update it, but the question was answered. – JesseN Aug 30 '18 at 18:21

1 Answers1

0

Did you try

def info = parsedJson.info.findAll{it.country.value == "USA"}

?

rdmueller
  • 10,742
  • 10
  • 69
  • 126