On Wed, Dec 21, 2016 at 11:58 AM, Dimitar Vassilev <
[email protected]> wrote:
> Good evening/morning/day,
> Quick one how can I parse a YAML file with groovy and snakeyaml
>
> I have a nested hash YAML like:
>
> pkgcolls:
> pkgcol1:
> software:Foo
> version:baz
> pkgcol2:
> software:baz
> version:Foo
>
> In Ruby I can do something like in the irb/file
> require 'yaml'
> thing = YAML.load_file('some.yml')
> puts thing.inspect
>
> How can I do similar thing in groovy using
>
> import org.yaml.snakeyaml.DumperOptions
> import org.yaml.snakeyaml.Yaml
>
> and the yaml.load(object) function?
> I would like to loop through the YAML structure and figure out which kind
> of loop to use.
> I'm interested in dealing directly with the pkgcol(1-N) attributes
> directly if possible.
> Thanks
>
Something like the following could be run in the GroovyConsole
```
@Grab(group='org.yaml', module='snakeyaml', version='1.17')
import org.yaml.snakeyaml.*
String yamlText = '''
pkgcolls:
pkgcol1:
software:Foo
version:baz
pkgcol2:
software:baz
version:Foo
'''
Yaml yaml = new Yaml()
def result = yaml.load(yamlText)
// or from a file
// new File('/tmp/test.yml').withReader('UTF-8') { reader ->
// def result = yaml.load(reader)
// ....
// }
result.pkgcolls.each {
assert it.key == 'pkgcol1' || it.key == 'pkgcol2'
}
println result.inspect()
```