wannamit
wannamit

Reputation: 117

How to Unmarshal and Marshal YAML in Go, while preserving white space?

I have a YAML like

data:
  label1:
    - someval1
    - someval2
  label2:
    - otherval1
    - otehrval2

Using YAML parser "gopkg.in/yaml.v2"

yaml.Unmarshal([]byte(yamlStr), &yamlObj)

# Some works and changes to yamlObj

s, _ := yaml.Marshal(&yamlObj)
fmt.Println(string(s))

This outputs:

data:
  label1:
  - someval1
  - someval2
  label2:
  - otherval1
  - otehrval2

The resulted YAML is correct but for my task I need lists (- values) indented as in original YAML. Is there a way to preserve those spaces and new lines?

Upvotes: 4

Views: 3279

Answers (1)

leberKleber
leberKleber

Reputation: 31


I think it would be very difficult to keep the original format. But as a workaround you can marshal your struct in a format which is near by your input format.

gopkg.in/yaml.v3 marshals in a more matching way as gopkg.in/yaml.v2

here is a little example: https://play.golang.org/p/gjxR83P7p0F Output:

V2: 
data:
  label1:
  - someval1
  - someval2
  label2:
  - otherval1
  - otehrval2

V3: 
data:
    label1:
        - someval1
        - someval2
    label2:
        - otherval1
        - otehrval2

Upvotes: 2

Related Questions