Search code examples
groovygroovyshell

How to get a value of a dynamic key in Groovy JSONSlurper?


The variable resp contains below JSON response -

{"name":"sample","address":{"country":"IN","state":"TN","city":"Chennai"}} 

I have planned using param1 variable to get the required key from JSON response, but I'm unable to get my expected results.

I'm passing the param1 field like - address.state

def actValToGet(param1){
    JsonSlurper slurper = new JsonSlurper();
    def values = slurper.parseText(resp)
    return values.param1 //values.address.state
}

I'm getting NULL value here -> values.param1

Can anyone please help me. I'm new to Groovy.


Solution

  • The map returned from the JsonSlurper is nested rather than than flat. In other words, it is a map of maps (exactly mirroring the Json text which was parsed). The keys in the first map are name and address. The value of name is a String; the value of address is another map, with three more keys.

    In order to parse out the value of a nested key, you must iterate through each layer. Here is a procedural solution to show what's happening.

    class Main {
        static void main(String... args) {
            def resp = '{"name":"sample","address":{"country":"IN","state":"TN","city":"Chennai"}}'
            println actValToGet(resp, 'address.state')
        }
    
        static actValToGet(String resp, String params){
            JsonSlurper slurper = new JsonSlurper()
            def values = slurper.parseText(resp)
            def keys = params.split(/\./)
            def output = values
            keys.each { output = output.get(it) }
            return output
        }
    }
    

    A more functional approach might replace the mutable output variable with the inject() method.

        static actValToGet2(String resp, String params){
            JsonSlurper slurper = new JsonSlurper()
            def values = slurper.parseText(resp)
            def keys = params.split(/\./)
            return keys.inject(values) { map, key -> map.get(key) }
        }
    

    And just to prove how concise Groovy can be, we can do it all in one line.

        static actValToGet3(String resp, String params){
            params.split(/\./).inject(new JsonSlurper().parseText(resp)) { map, key -> map[key] }
        }
    

    You may want to set a debug point on the values output by the parseText() method to understand what it's returning.