I have a JSON document structured similar to below, and I am trying to parse it in Groovy. Basically for each School (School Info), I want to grab the SCHOOL_COUNTRY
and other fields. I am trying this code below but it is not returning what I need. For each school listed (1,000's), I want to grab only specific parts, for instance:
def parseJSON(long id) {
JSONFile fileInstance = JSONFile.get(id)
def json = new JsonSlurper().setType(RELAX).parse(new FileReader(fileInstance.filePath))
def schoolInfo = json.SCHOOL_INFO
def schoolName = json.SCHOOL_INFO.SCHOOL_NAME
schoolInfo.each {
render(schoolInfo.SCHOOL_NAME)
}
}
So basically for each school, just print out the name of the school. The JSON structure:
[{
"SCHOOL_INFO": {
"SCHOOL_COUNTRY": "Finland",
"SCHOOL NAME": "Findland Higher Learning"
},
"LOCATION": {
"LONGITUDE": "24.999",
"LATITUDE": "61.001"
}
}]
I'm not sure if it's the only bug but you can't read schoolInfo.SCHOOL_NAME
in each
. SCHOOL_NAME
is property of json.SCHOOL_INFO
so it.SCHOOL_NAME
is proper way to access it. Take look at example below:
import groovy.json.JsonSlurper
def jsonAsText = '''[{
"SCHOOL_INFO": {
"SCHOOL_COUNTRY": "Finland",
"SCHOOL NAME": "Findland Higher Learning"
},
"LOCATION": {
"LONGITUDE": "24.999",
"LATITUDE": "61.001"
}
}]'''
def json = new JsonSlurper().parseText(jsonAsText)
def schoolInfo= json.SCHOOL_INFO
schoolInfo.each{
println it."SCHOOL NAME"
}
It prints:
Findland Higher Learning
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With