2

I am using snakeYaml to convert a String in YAML format to Groovy Map.

@Grab(group='org.yaml', module='snakeyaml', version='1.17')
import org.yaml.snakeyaml.Yaml

Yaml yaml = new Yaml()

Map config = yaml.load(new File('config.yaml').text)

I want to reach now the opposite : Given a Groovy Map, i want to convert it to String in YAML format WITHOUT WRITING THE STRING in a FILE.

I found groovy.yaml.YamlBuilder. However, the groovy compiler of the environment is old and this class is not found.

Ideally, the same lib (snakeYaml) can handle the opposite case. But no way to get it work.

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • 1
    Does this answer your question? [How do I write to a YAML file using SnakeYaml?](https://stackoverflow.com/questions/24949505/how-do-i-write-to-a-yaml-file-using-snakeyaml) – cfrick Sep 03 '20 at 15:46
  • Not the same. I want to get the String in Yaml format without writing the String in a text – Abdennour TOUMI Sep 03 '20 at 16:30
  • 3
    Sorry, but maybe you have to be more explicit - I don't see how `yaml.dump([a: 1])` is not what you are asking? "Encode a map datastrcuture to YAML" – cfrick Sep 03 '20 at 16:36
  • Agree with @cfrick above, the signature of dump is `String dump(Object data)`, i.e. the [dump method](https://www.javadoc.io/doc/org.yaml/snakeyaml/1.19/org/yaml/snakeyaml/Yaml.html#dump-java.lang.Object-) returns a `String` which I believe is what you are asking for? – Matias Bjarland Sep 04 '20 at 08:30

1 Answers1

1

yes yaml.dump() is the answer


Map config = [kind: 'Pod', metadata:[name: app]]

Yaml yaml = new Yaml()

assert yaml.dump(config) == '''kind: Pod
metadata:
  name: app
'''
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254