YAML and TOML
Groovy 5 ships groovy-yaml and groovy-toml, so a script reads a configuration file in either format without a dependency. The API is the one of the JSON lesson: a slurper in, a builder out.
YAML
yaml.groovy
import groovy.yaml.YamlSlurper
def text = '''name: Ada
skills:
- Groovy
- Java
server:
host: localhost
port: 8080
'''
def data = new YamlSlurper().parseText(text)
println data.name
println data.skills
println data.skills.getClass().name
println data.server.port
groovy yaml.groovy
Ada
[Groovy, Java]
java.util.ArrayList
8080
A YAML mapping is a map and a sequence is a list, as in JSON, and the property access is the same. The class name line proves the last point: the value is an ArrayList, not a special YAML type.
Write YAML
buildyaml.groovy
import groovy.yaml.YamlBuilder
def builder = new YamlBuilder()
builder {
server {
host 'localhost'
port 8080
}
}
println builder.toString()
groovy buildyaml.groovy
---
server:
host: "localhost"
port: 8080
YamlBuilder writes a document from nested closures, and the output starts with the document marker ---. A null property is left out, which is what a configuration file wants.
TOML
toml.groovy
import groovy.toml.TomlSlurper
def text = '''[server]
host = "localhost"
port = 8080
[[users]]
name = "Ada"
'''
def config = new TomlSlurper().parseText(text)
println config.server.host
println config.server.port
println config.users[0].name
groovy toml.groovy
localhost
8080
Ada
A TOML table is a map and a double-bracket array of tables is a list of maps, so the access is the one of the other two formats. TomlBuilder writes the format back; a Groovy script that reads a Gradle version catalog reads TOML exactly this way.
Related
- JSON with JsonSlurper and JsonOutput: the same shape in another format.
- Version catalogs: a real TOML file of a Gradle build.
Article author: Arthur Isaev