tags:

views:

207

answers:

2

as a tcl developer starting with groovy, I am a little bit surprised about the list and map support in groovy. Maybe I am missing something here.

I am used to convert between strings, lists and arrays/maps in tcl on the fly. In tcl, something like

"['a':2,'b':4]".each {key, value -> println key + " " + value}

would be possible, where as in groovy, the each command steps through each character of the string.

This would be much of a problem is I could easily use something like the split or tokenize command, but because a serialized list or map isn't just "a:2,b:4", it is a little bit harder to parse.

It seems that griffon developers use a stringToMap library (http://code.google.com/p/stringtomap/) but the example can't cope with the serialized maps either.

So my question is now: what's the best way to parse a map or a list in groovy?

Cheers, Ralf

PS: it's a groovy question, but I've tagged it with grails, because I need this functionality for grails where I would like to pass maps through the URL

+1  A: 

I think you are looking for a combination of ConfigObject and ConfigSlurper. Something like this would do the trick.

def foo = new ConfigObject()
foo.bar = [ 'a' : 2, 'b' : 4 ]

// we need to serialize it
new File( 'serialized.groovy' ).withWriter{ writer ->
  foo.writeTo( writer )
}

def config = new ConfigSlurper().parse(new File('serialized.groovy').toURL())    

// highest level structure is a map ["bar":...], that's why we need one loop more
config.each { _,v ->
    v.each {key, value -> println key + " " + value}
}
Grega Kešpret
thanx, good to know about the slurper!
Ralf
+7  A: 

You might want to try a few of your scenarios using evaluate, it might do what you are looking for.

def stringMap = "['a':2,'b':4]"
def map = evaluate(stringMap)

assert map.a == 2
assert map.b == 4

def stringMapNested = "['foo':'bar', baz:['alpha':'beta']]"
def map2 = evaluate(stringMapNested)

assert map2.foo == "bar"
assert map2.baz.alpha == "beta"
John Wagenleitner
thanx. I guess this is close to what I was looking for!
Ralf
wow. just noticed that the solution is quite a big security risk!If the data is passed through the URL and we just do an evaluate() on it, everything can happen!So I guess the JSON solution will be the better way...
Ralf