Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a YAML file in groovy?

Tags:

yaml

groovy

say if you have a file called example.yaml which contains the following: - subject: maths.

How do i grab the string after - subject?

I already can read the contents of the file but want to know how to grab a specific string from it.

note: i know regex may help but have never used it and would appreciate any help.

like image 658
user3412172 Avatar asked Jan 18 '17 23:01

user3412172


People also ask

Is YAML groovy?

YamlSlurper is a class that parses YAML text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String . The class comes with a bunch of overloaded parse methods plus some special methods such as parseText and others.

What is SnakeYAML?

SnakeYAML is a YAML-parsing library with a high-level API for serialization and deserialization of YAML documents. The entry point for SnakeYAML is the Yaml class, similar to how the ObjectMapper class is the entry point in Jackson.


2 Answers

UPDATE Dec-2021: The documentation of the SnakeYAML project is not accessible anymore on Bitbucket, and a quick google search did not show any alternate repository, so I guess this project either has gone closed source or it has died.

So I am adding here the same example, but implemented with the native YAMLSlurper (Groovy 3.x+):

    import groovy.yaml.YamlSlurper          def exampleYaml = '''\     ---     - subject: "maths"     - subject: "chemistry"     '''          List example = new YamlSlurper().parseText(exampleYaml) //If your source is a File //    List example = new YamlSlurper().parse("example.yaml" as File)          example.each{println it.subject}  

For previous versions (Original answer):

snakeyaml is a library to parse YAML files. Easy to use in groovy.

UPDATE: changed type of the example variable to List, as the example file's top level element is a collection

    @Grab('org.yaml:snakeyaml:1.17')          import org.yaml.snakeyaml.Yaml          Yaml parser = new Yaml()     List example = parser.load(("example.yaml" as File).text)          example.each{println it.subject}  

Full documentation of snakeyaml:

https://bitbucket.org/asomov/snakeyaml/wiki/Documentation

like image 188
Luis Muñiz Avatar answered Oct 11 '22 16:10

Luis Muñiz


FWIW, the upcoming (as time of this writing) Groovy version 3.0 has direct support for yaml: http://docs.groovy-lang.org/next/html/api/groovy/yaml/package-summary.html with the traditional YamlSlurper / YamlBuilder combo You could always switch to this not-yet-officially-released version.

[Edited] that version 3.0.x is now officially available, with the groovy.yaml package http://docs.groovy-lang.org/latest/html/api/groovy/yaml/package-summary.html

like image 28
Patrice M. Avatar answered Oct 11 '22 15:10

Patrice M.