I have a string of JSON that I've retrieved from an API. I'm using JsonSlurper
to parse the string into JSON, but I'm unsure how to handle when the key contains spaces.
An example of the JSON is:
{
"total": 3,
"page": 1,
"totalPages": 1,
"results": [{
"person name": "John Doe",
"date of birth": "01/01/1990",
"date of registration": "01/01/2016",
"notes": "default user",
}]
}
I want to iterate through the results that are returned and find a specific person by person name
. The code I have so far, which I doubt will work is:
final RestBuilder rest = new RestBuilder()
JsonSlurper slurper = new JsonSlurper()
def response = rest.get("http://example.com/api/getPeople")
def json = slurper.parseText(response.text)
def jsonResults = json.results
jsonResults.each { res ->
assert res.personName == 'John Doe'
}
What is the correct way to get "person name"
since it has spaces?
Wrap it with '
:
import groovy.json.JsonSlurper
def input = '''{
"total": 3,
"page": 1,
"totalPages": 1,
"results": [{
"person name": "John Doe",
"date of birth": "01/01/1990",
"date of registration": "01/01/2016",
"notes": "default user",
}]
}'''
def json = new JsonSlurper().parseText(input)
json.results.each { res ->
assert res.'person name' == 'John Doe'
}