Slimy43
Slimy43

Reputation: 341

Using Groovy 3 YamlBuilder with Yaml that contains a hyphen

I'm trying to write a Groovy 3 script that uses yamlbuilder to write a yaml file. I have it working on almost everything apart from;

execution:
  set-props:
    url:http://myhouse.net
    port:8000

How do I write a map that allows the use of a hyphen in the name? Following my previous work I foolishly tried;

def setprops=[:]
setprops=(["url":"http://myhouse.net","port":"8000"])
execution.set-props=setprops

Which gives me an error 'The LHS of an assignment should be a variable or a field'.

If I just use execution.setprops then it works fine, but of course the resulting yaml from yaml(execution) is invalid.

I think if the set-props was a a key/value pair then it could go into quote and everything would be good. But because it is part of the structure I don't know what needs to be done.

Upvotes: 1

Views: 809

Answers (1)

cfrick
cfrick

Reputation: 37008

You can use strings as "methods" and the builder will create your intermediate structures from them:

import groovy.yaml.YamlBuilder

def b = new YamlBuilder()

b.execution {
    "set-props"(
        url: "..."
    )
}

println b

Or to continue on your example: You can create the whole map and use is as argument, where you want to have that content.

def setprops=["set-props": [url:"..."]]
b.execution(setprops)

Both result in:

---
execution:
  set-props:
    url: "..."

Note that the first version nests via passed closures and then passes in the map. The second bit just passes a nested map.

Upvotes: 2

Related Questions