Accessing elements of a map of maps using a string

2019-05-26 00:04发布

问题:

Given I have a map like:

def myMap = [ b : [ c:"X" ] ]

And a string

def key = 'b.c'

I'd like to see my options for using the key to get to the value 'X'.

I have come up with two ways of achieving this myself, but I am not very happy with these solutions:

 1) Eval.me("theMap", myMap, "theMap.$key")
 2) mayMap."$key.split('\\.')[0]"."$key.split('\\.')[1]"

Anyone has a better way of doing this in Groovy?

回答1:

A convenient way is to use ConfigObject which implements Map.

def myMap = [b:[c:'X', d: 'Y'], a:[n:[m:[x:'Y']]]] as ConfigObject
def props = myMap.toProperties()

assert props['b.c'] == 'X'
assert props.'b.c' == 'X'
assert props.'a.n.m.x' == 'Y'

Pros:

  • No more splitting.
  • No more evaluating.


回答2:

IMHO its not the ConfigObject, that does the trick, its the Properties (from ConfigObject.toProperties()). Look & try:

def props = new ConfigSlurper().parse("""
b {
 c = 'X'
 d = 'Y'
}
a {
 n {
   m {
     x:'Y'
   }
 }
}""")

assert props['b.c'] == 'X'
assert props.'b.c' == 'X'
assert props.'a.n.m.x' == 'Y'
'passed'

Assertion failed:

assert props['b.c'] == 'X'
       |    |       |
       |    [:]     false
       [b:[c:X, d:Y], a:[n:[m:[:]]], b.c:[:]]

    at ConsoleScript7.run(ConsoleScript7:14)

and I really wish, the ConfigObject could be indexed with such combined keys like above



标签: map groovy