Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy map dot keys to nested map

I have a map with keys in dot notation, but I need it as a nested map.

[test.key.one: 'value1', text.key.two: 'value2']

Now the result should be

[
    test: [
        key: [
            one: 'value1',
            two: 'value2'
        ]
    ]
]

And here is my idea of code

def extract(String key, String value) {

    if(key.contains(".")) {
        def (String target, String subKey) = key.split('\\.', 2)
        return ["$target": extract(subKey, value)]
    } else {
        return ["$key": extractType(value)]
    }

}

But I want to know if there is any groovy magic doing this in a closure or witht he help of other goodies to make it simpler.

like image 893
Pascal Avatar asked Jan 12 '17 06:01

Pascal


1 Answers

There is one handy class: groovy.util.ConfigSlurper

def map = ['test.key.one': 'value1', 'test.key.two': 'value2']
def props = new Properties()
props.putAll(map)
println new ConfigSlurper().parse(props) // [test:[key:[two:value2, one:value1]]]

The only drawback is that it expects java.util.Properties instance, so you need to create one from the map.

like image 100
Dany Avatar answered Sep 28 '22 06:09

Dany