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.
UPDATE (2020)
Groovy 3 now includes a groovy.yaml.YamlSlurper
(similar to JsonSlurper
/ XmlSlurper
)
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:
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
Here is an example: https://github.com/apache/groovy/blob/bdb2f7a482a4daec2bee01acd5590241c356e966/subprojects/groovy-yaml/src/spec/test/groovy/yaml/YamlParserTest.groovy#L83
BTW, multiple docs in one yaml file is supported since Groovy 4.0.0. For example, https://github.com/apache/groovy/blob/bdb2f7a482a4daec2bee01acd5590241c356e966/subprojects/groovy-yaml/src/spec/test/groovy/yaml/YamlParserTest.groovy#L109
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.