Search code examples
javastringgroovyhashmapstring-interpolation

How to get a value from a property of a nested map with dot notation in Groovy using string interpolation


I receive a dot notated string from parameter, e.g. "attr1.attr2.attr3". I have an object of data type LinkedHashMap<String, Object> mapObject. It has a value that can be accessed this way: mapObject.attr1.attr2.attr3.

When I try to access the field in this way: mapObject."${attr1.attr2.attr3}, I receive a MissingPropertyException, as groovy translates it as a String: mapObject."attr1.attr2.attr3" and that property, obviously, does not exist. I have managed to solve it using the Eval.java class Eval.x() method this way: Eval.x(mapObject,"x.${attr1.attr2.attr3}"), but this is too slow even for a snail.

Does there exist a way where I can get the value of a nested property of a map knowing only the dot notated path?

Here is my code:

def superCoolMethod(String dotNotatedPath, LinkedHashMap<String, Object> MapObject){
def valueINeedToGetFromTheMapObject = MapObject."${dotNotatedPath}"
// Other stuff unimportant for this question.

Solution

  • You can split the path on . (quote it for the regexp) and then reduce over the path using your data. E.g.

    def data = [a: [b: [c: 42]]]
    def path = "a.b.c"
    
    println path.split(/\./).inject(data){ m, p -> m?.getAt(p) }
    // → 42