Home > Groovy > SnakeYAML and Groovy

SnakeYAML and Groovy

I had some fun playing with SnakeYAML and Groovy the other day. Below are some of my results. If you want to run this in your groovyConsole, you need to download SnakeYAML and add the snakeyaml-<version>.jar to your classpath.

From YAML to Groovy:

import org.yaml.snakeyaml.Yaml

Yaml yaml = new Yaml()
def obj = yaml.load("""
a: 1
b: 2
  - aaa
  - bbb""")

assert obj.a == 1
assert obj.b == 2
assert obj.c == ["aaa", "bbb"]

From Groovy to YAML:

import org.yaml.snakeyaml.Yaml

def map = [name: "Pushkin", aliases: ['P', 'Push']]
Yaml yaml = new Yaml()
String output = yaml.dump(map)

assert output ==
'''name: Pushkin
aliases: [P, Push]

Isn’t YAML so much simpler and cleaner than XML? Why aren’t more of us using YAML with Java and Groovy?

  1. hbagchi
    January 19, 2010 at 9:23 pm

    What is the benefit of using YAML vis-a-vis JSON? Looks like to JSON to me?

  2. January 21, 2010 at 8:30 pm

    @hbagchi According to the YAML 1.2 spec, YAML is an official subset of JSON, so you’re right – it does look like JSON. I don’t yet know the benefits of YAML vs. JSON – I was looking at YAML vs. XML, since I knew that Ruby and Rails seemed to prefer YAML over XML.

  3. alex
    April 21, 2010 at 7:34 am

    @hbagchi : I guess JSON does not support recursive objects.

  4. February 25, 2012 at 6:12 pm

    very useful post
    BTW, I had troubles escaping chars with snake yaml

    could anybody give a hand with this question: http://stackoverflow.com/questions/9448918/snakeyaml-escaping-new-line-characters-in-yaml

  5. October 14, 2017 at 4:59 am

    The Problem with YAML: One little Typo breaks your syntax for e.g. one EmptySpace, evt. one commata breaks it all. Another issue with both yaml and json: missing semantics.

  1. January 14, 2010 at 2:33 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: