Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - JsonSlurper Parsing JSON file

Tags:

json

groovy

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"
     }
}]
like image 294
pinkdevelops Avatar asked Sep 10 '14 21:09

pinkdevelops


1 Answers

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
like image 140
Paweł Piecyk Avatar answered Sep 26 '22 02:09

Paweł Piecyk