使用groovy脚本解析JSON(使用JsonSlurper) [英] Parse JSON using groovy script (using JsonSlurper)

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

问题描述

我只有两天大的时间,我需要解析一个具有以下结构的json文件.我的实际想法是我需要根据不同的顺序在不同的环境中运行一组作业,因此我想出了这种json格式作为groovy的输入文件

I am just two days old to groovy, I need to parse a json file with below structure. My actual idea is I need to run a set of jobs in different environments based on different sequences, so I came up with this format of json as a input file to my groovy

{
    "services": [{
        "UI-Service": [{
            "file-location": "/in/my/server/location",
            "script-names": "daily-batch,weekly-batch,bi-weekly-batch",
            "seq1": "daily-batch,weekly-batch",
            "seq2": "daily-batch,weekly-batch,bi-weekly-batch",
            "DEST-ENVT_seq1": ["DEV1", "DEV2", "QA1", "QA2"],
            "DEST-ENVT_seq2": ["DEV3", "DEV4", "QA3", "QA4"]
        }]
    }, {
        "Mobile-Service": [{
            "file-location": "/in/my/server/location",
            "script-names": "daily-batch,weekly-batch,bi-weekly-batch",
            "seq1": "daily-batch,weekly-batch",
            "seq2": "daily-batch,weekly-batch,bi-weekly-batch",
            "DEST-ENVT_seq1": ["DEV1", "DEV2", "QA1", "QA2"],
            "DEST-ENVT_seq2": ["DEV3", "DEV4", "QA3", "QA4"]
        }]
    }]
}

我尝试了以下脚本来解析json

I tried below script for parsing the json

        def jsonSlurper = new JsonSlurper()
        //def reader = new BufferedReader(new InputStreamReader(new FileInputStream("in/my/location/config.json"),"UTF-8"))
        //def data = jsonSlurper.parse(reader)
        File file = new File("in/my/location/config.json")
        def data = jsonSlurper.parse(file)

        try{
            Map jsonResult = (Map) data;
            Map compService = (Map) jsonResult.get("services");
            String name = (String) compService.get("UI-Service");
            assert name.equals("file-location");

        }catch (E){
            println Exception
        }

我需要先阅读所有服务(UI服务,移动服务等),然后阅读其元素及其值

I need to first read all the services (UI-service, Mobile-Service, etc..) then their elements and their value

推荐答案

从JsonParser对象读取的示例:

Example for reading from JsonParser object:

def data = jsonSlurper.parse(file)
data.services.each{ 
    def serviceName = it.keySet()
    println "**** key:${serviceName}  ******"
    it.each{ k, v ->
        println "element name: ${k}, element value: ${v}"
    }
}

其他选项:

println data.services[0].get("UI-Service")["file-location"]
println data.services[1].get("Mobile-Service").seq1

这篇关于使用groovy脚本解析JSON(使用JsonSlurper)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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