简体   繁体   中英

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 aa 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM