groovyyamlbuilder

Convert Map<String, List<String>> to Yaml using YamlBuilder


i want to convert a json

{"test": "1,2,3,4"}

into yaml of the form:

---
test:
  - 1
  - 2
  - 3
  - 4

for this i tried to use the following groovy snippet:

def json = new groovy.json.JsonSlurper().parseText('{"test": "1,2,3,4"}')
println json
def ymlMap = json.collectEntries { k, v -> [k , v.split(', ')] }
def yml = new groovy.yaml.YamlBuilder()
yml ymlMap
println yml.toString()

but it prints

---
test:
- "1,2,3,4"

Any hints how to use yamlbuilder correct?


Solution

  • haha, your split-regex contains one space too much:

    json.collectEntries { k, v -> [k , v.split(',')] }
    

    Then it prints:

    ---
    test:
    - "1"
    - "2"
    - "3"
    - "4"
    

    With that space in place, the value is not split and output as-is.