Groovy - JsonSlurper Parsing JSON file

I have a JSON document similar to the one below and I'm trying to parse it in Groovy. Basically for each school (school information) I want to capture SCHOOL_COUNTRY and other fields. I am trying to use this code below, but it does not return what I need. For each school listed (1000), I want to capture only certain parts, for example:

 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. JSON structure:

 [{ "SCHOOL_INFO": { "SCHOOL_COUNTRY": "Finland", "SCHOOL NAME": "Findland Higher Learning" }, "LOCATION": { "LONGITUDE": "24.999", "LATITUDE": "61.001" } }] 
+5
source share
3 answers

I'm not sure this is the only mistake, but you cannot read schoolInfo.SCHOOL_NAME in each . SCHOOL_NAME is a property of json.SCHOOL_INFO , so it.SCHOOL_NAME is the right way to access it. See an 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" } 

He prints:

 Findland Higher Learning 
+8
source

Here you go:

 import groovy.json.JsonSlurper def t = """[{ "SCHOOL_INFO": { "SCHOOL_COUNTRY": "Finland", "SCHOOL NAME": "Findland Higher Learning" }, "LOCATION": { "LONGITUDE": "24.999", "LATITUDE": "61.001" } }]""" def slurper = new JsonSlurper().parseText(t) slurper.each { println it.SCHOOL_INFO."SCHOOL NAME" } 

I am not sure there should be a _ in SCHOOL NAME.

+2
source
 println it.SCHOOL_INFO."SCHOOL NAME" 

This should work without a sign.

+1
source

Source: https://habr.com/ru/post/1202281/


All Articles