Groovy-JsonSlurper解析JSON文件 [英] Groovy - JsonSlurper Parsing JSON file

查看:2397
本文介绍了Groovy-JsonSlurper解析JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构类似于下面的JSON文档,并且我试图在Groovy中对其进行解析.基本上,对于每个学校(学校信息),我都想获取SCHOOL_COUNTRY和其他字段.我正在下面尝试此代码,但未返回我需要的代码.对于每个列出的学校(1,000所),我只想获取特定部分,例如:

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)
    }
}

因此,基本上,对于每所学校,只需打印出学校名称即可. JSON结构:

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"
     }
}]

推荐答案

我不确定这是否是唯一的错误,但是您无法阅读each中的schoolInfo.SCHOOL_NAME. SCHOOL_NAMEjson.SCHOOL_INFO的属性,因此it.SCHOOL_NAME是访问它的正确方法.请看下面的示例:

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"
}

它打印:

Findland Higher Learning

这篇关于Groovy-JsonSlurper解析JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆