How do I parse a YAML file in groovy?

后端 未结 2 944
星月不相逢
星月不相逢 2021-01-01 10:16

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

How do i grab the string after - subject

2条回答
  •  误落风尘
    2021-01-01 10:45

    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:

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

提交回复
热议问题