Pranav Shah
Pranav Shah

Reputation: 3323

How to work with null or missing key/value pair in JSON in Groovy

The code below shows a sample JSON that I am trying to evaluate.

The fist 2 assert statements work, but the rest don't. Any help will be great.

Code:

import groovy.json.*

def jsonText = '''
{
    "message": {

            "employees": [{
                "firstName": "John",
                "lastName": "Doe",
                "age": 1
            }, {
                "firstName": "Anna",
                "lastName": "Smith",
                "age": 5
            }, {
                "firstName": "Peter",
                "lastName": "Jones"

            }],

        "body": "Some message"
    }
}        
'''

def json = new JsonSlurper().parseText(jsonText)

def message= json.message
assert message.employees[0].age == 1
assert message.employees.size() == 3

// How to make the following tests work.  Are there any options?
assert message.employees.age.size() == 2      // How many employees have an age key/value pair?

// What's the sum of the ages, if the value does not exist use 0

assert message.employees.sum { it.age==null?0:it.age } == 6  // Could I use some sort of null check?
assert message.employees.age.sum() == 6  // Is there a way to specify the default value

Upvotes: 1

Views: 516

Answers (1)

tim_yates
tim_yates

Reputation: 171194

For the first,

// How many employees have an age key/value pair?
assert message.employees.findAll { it.age }.size() == 2
// Or
assert message.employees.age.findAll().size() == 2

And for the sum:

// You could use the elvis operator
assert message.employees.sum { it.age ?: 0 } == 6

Upvotes: 3

Related Questions