Parse YAML using YamlSlurper

In Teneo Studio, you can use the YamlSlurper class to read in YAML formatted strings which is a common format for structured documents. This class is already included in Groovy 3 so you just need import it using the following code:

import groovy.yaml.YamlSlurper

Suppose that you have the following YAML saved in a string named sYaml:

def sYaml = '''
position: "System Developer"
location: "New York"
applicants:
- name: "Tommy"
  programming languages:
  - Groovy
  - Python
  - Java
- name: "John"
  programming languages:
  - Ruby
  - php
'''

Use the following code to parse this YAML and save it in a map called mYamlParsed:

def mYamlParsed = new YamlSlurper().parseText(sYaml)

See the class of mYamlParsed and its content below:

If you have the YAML file uplodaded in your Resource files, please use the following code to parse it:

URL url = this.getClass().getClassLoader().getResource('your_file.yml')
URI uri = url.toURI()
File file = new File(uri)
def mYamlParsed = new YamlSlurper().parseText(file.getText())

The code in this post is an example on how you can parse YAML in your Teneo solution. You can find another post here which shows an example on how to parse XML formatted data, and here for parsing and building of JSON formatted data. Have you been using YAML yourself already?

1 Like