-1

Suppose I have nested map like this

def someMap = [
   a : [
      b : [
         c : "value",
         d : "anothervalue"
      ]
   ]
]

I get the key at runtime as a string. Say it is "a.b.c"

How can I pull the value out of the map?

I know I can do myMap.a.b.c but for me, "a.b.c" is single string, I found out about at runtime?

Thanks

More Than Five
  • 9,959
  • 21
  • 77
  • 127
  • 1
    https://stackoverflow.com/questions/58052344/how-to-get-a-value-of-a-dynamic-key-in-groovy-jsonslurper – tim_yates Feb 13 '20 at 17:09
  • 1
    https://stackoverflow.com/questions/9180039/way-to-deep-traverse-a-groovy-object-with-dot-in-string-using-gpath – tim_yates Feb 13 '20 at 17:11
  • 1
    https://stackoverflow.com/questions/30157787/referencing-groovy-variable-as-part-of-json-path – tim_yates Feb 13 '20 at 17:13
  • 1
    Does this answer your question? [How to get a value of a dynamic key in Groovy JSONSlurper?](https://stackoverflow.com/questions/58052344/how-to-get-a-value-of-a-dynamic-key-in-groovy-jsonslurper) – Daniel Feb 13 '20 at 23:01
  • Do you know for sure that keys will never have a dot (`.`) in them? – Jeff Scott Brown Jul 21 '21 at 16:04

1 Answers1

0

You could just go down the nodes likes this and try to get the respective child:

def key = "a.b.c"
def entry = someMap
key.split('\\.').each { entry = entry?.get(it) }
println entry?.value
MushyPeas
  • 2,469
  • 2
  • 31
  • 48