Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

Yaml is a straightforward machine parsable data serialization format designed for human readability and interaction with scripting languages. One of its reasons for popularity is that XML can sometimes be quite verbose and cumbersome. Groovy's XML capabilities make XML less verbose (e.g. through its builder notation for creating XML) and less cumbersome (e.g. its excellent XML processing capabilities). Even so, there may be times when you need to or prefer to use Yaml over XML. Here are some examples of how to use Groovy with the JYaml library.

First, reading simple lists:

Code Block
// require(url:'http://jyaml.sourceforge.net', jar:'jyaml.jar', version:'1.0')
import org.ho.yaml.Yaml

def input = '''
- 1
- apple
- orange
'''
assert Yaml.load(input) == [1, 'apple', 'orange']

Reading maps:

Code Block
// ...
input = '''
Name: Andre Agassi
Height: 5'11'' (180 cm)
Birthplace: "Las Vegas, Nevada, USA"
Turned Pro: 1986
'''

def player = Yaml.load(input)
assert player.Birthplace == "Las Vegas, Nevada, USA"
assert player['Turned Pro'] == 1986

Reading into classes:

Code Block
// ...
class Staff {
    def firstname, lastname, position
}

input = '''
firstname: John
lastname: Connor
position: Resistance Leader
'''
Staff s = Yaml.loadType(input, Staff)
println s.dump()
// => <Staff@c05d3b firstname=John lastname=Connor position=Resistance Leader>

Writing lists:

Code Block
// ...
def list = ['a, b', 123456]
println Yaml.dump(list)

This produces:

No Format
---
- "a, b"
- 123456