简体   繁体   中英

Parse JSON using groovy script (using JsonSlurper)

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

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
        }

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

Or you could do something like:

new JsonSlurper().parseText(jsonTxt).services*.each { serviceName, elements ->
    println serviceName
    elements*.each { name, value ->
        println "    $name = $value"
    }
}

But it depends what you want (and you don't really explain in the question)

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

other options:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM