0

I'm trying to create yaml file from a map with yamlBuilder but it's not in the right context that I need it to be.

For example: Map mymap = [1: "a, b, c ,d", 2: "y, d, x"]

The yamlfile that I want to look like:

-Content:
    -1:
         -a
         -b
         -c
         -d
    -2:
         -y
         -d
         -x

How the syntax of creation the yaml file should be? I've tried:

def yamlFile = new YamlBuilder()
yamlFile{
myMap
}

but this is not the same design as I need it to be.

Thanks

Saar Gamzo
  • 57
  • 4
  • Do you mean to use lists instead of a coma separated string for the values in your map? IE: `Map mymap = [1: ["a", "b", "c" ,"d"], 2: ["y", "d", "x"]]` – tim_yates Oct 21 '22 at 09:01

1 Answers1

1

Ok, so with the map you dropped in the question, you can do:

import groovy.yaml.YamlBuilder

Map mymap = [1: "a, b, c ,d", 2: "y, d, x"]

def config = new YamlBuilder()
 
config {
    "Content" mymap
}

println config.toString()

Which prints

---
Content:
  "1": "a, b, c ,d"
  "2": "y, d, x"

As you can see, your input map just has String values, not lists...

If you meant to give your input map as:

Map mymap = [1: ["a", "b", "c", "d"], 2: ["y", "d", "x"]]

Then the above code prints out

---
Content:
  "1":
  - "a"
  - "b"
  - "c"
  - "d"
  "2":
  - "y"
  - "d"
  - "x"

Which is what you say you want...

If the original map was correct and you're being sent comma separated Strings to represent lists, then you'll need to munge them yourself into lists

Map mymap = [1: "a, b, c ,d", 2: "y, d, x"]

mymap = mymap.collectEntries { k, v ->
    [k, v.split(",")*.trim()]
}

def config = new YamlBuilder()
 
config {
    "Content" mymap
}

println config.toString()

Which again gives you

---
Content:
  "1":
  - "a"
  - "b"
  - "c"
  - "d"
  "2":
  - "y"
  - "d"
  - "x"
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • Thanks! Unfortunately I can't use yamlBuilder and should snakeYaml only. Do you know if there is option to create yaml file from map object as yamlBuilder? – Saar Gamzo Oct 24 '22 at 09:32