groovysnakeyaml

Converting YAML file to Groovy map results with snakeyaml returns in undesirable format


I'm attempting to parse a YAML file using snakeyaml in Groovy. The goal is to create a map that I can ultimately search from.

The file I'm using is structured like:

maintainers:
  - component: PowerPuff Girls
    pg: Utonium Labs
    people:
      - Buttercup
      - Blossom
      - Bubbles
    files:
      - sugar/*
      - spice/*
      - things/*nice*
      - chemicalx/*
  - component: Gangreen Gang
    pg: Villians
    people:
      - Ace
      - Snake
      - Big Billy
    files:
      - ace/*
      - snake/*

The problem is: When I create a map and return the value, the maintainers value is throwing off the format from what I would hope for. Additionally, it seems like none of the String values are converted to a String. The output is:

[maintainers:[[component:PowerPuff Girls, pg:Utonium Labs, people:[Buttercup, Blossom, Bubbles], files:[sugar/*, spice/*, things/*nice*, chemicalx/*]], [component:Gangreen Gang, pg:Villians, people:[Ace, Snake, Big Billy], files:[ace/*, snake/*]]]]

In a perfect world, I would have:

[component: 'PowerPuff Girls', pg: 'Utonium Labs', people: ['Buttercup', 'Blossom', 'Bubbles'], files: ['sugar/*','spice/*','things/*nice*', 'chemicalx']], 
[component: 'Gangreen Gang', pg: 'Villians', people: ['Ace', 'Snake', 'Big Billy'], files: ['ace/*','snake/*']]

I must be missing something silly with reformatting this map. I welcome all suggestions!

Step 1: Loading the file as Map

Yaml yaml = new Yaml()
Map yamlMap = yaml.load(yamlFile)

Step 2: Returning map to observe format return yamlMap

Results in:

[maintainers:[[component:PowerPuff Girls, pg:Utonium Labs, people:[Buttercup, Blossom, Bubbles], files:[sugar/*, spice/*, things/*nice*, chemicalx/*]], [component:Gangreen Gang, pg:Villians, people:[Ace, Snake, Big Billy], files:[ace/*, snake/*]]]]

I attempted to define individual keys and values separately and reconstruct them, but it wasn't pulling the groupings as expected. E.g: def myVariable = yamlMap['maintainers']['component']


Solution

  • probably the nearest to your ideal world format is json.

    yamlMap.maintainers.each{ i-> println groovy.json.JsonOutput.toJson(i) }
    

    if you want to search for item(s) where component matches some value:

    println yamlMap.maintainers.find{i-> i.component=='Gangreen Gang' } // equals
    println yamlMap.maintainers.find{i-> i.component=~'green' }         // regex match
    println yamlMap.maintainers.findAll{i-> i.component=~'green' }      // find all
    println yamlMap.maintainers.findIndexOf{i-> i.component=~'green' }  // return index instead of element
    

    more groovy methods on list/collection:

    https://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/List.html