go-yaml / yaml

YAML support for the Go language.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Force marshaler to use multi-line for string with `\n`

1755 opened this issue · comments

Hi!

I'm using gopkg.in/yaml.v3 version of the library and trying to serialize string with a lot of lines breaked with \n symbol.

Here is minimized code snippet which reproduces the issue(?):

type BugOrNotToBug struct {
	Description string `yaml:"description"`
}

b1 := BugOrNotToBug{
	Description: "Hello\nWorld",
}
b2 := BugOrNotToBug{
	Description: "Hello\n World",
}
b3 := BugOrNotToBug{
	Description: "Hello \nWorld",
}

c1, _ := yaml.Marshal(b1)
fmt.Printf("C1:\n%s\n", c1)

c2, _ := yaml.Marshal(b2)
fmt.Printf("C2:\n%s\n", c2)

c3, _ := yaml.Marshal(b3)
fmt.Printf("C3:\n%s\n", c3)

I've got the next results:

C1:
description: |-
    Hello
    World

C2:
description: |-
    Hello
     World

C3:
description: "Hello \nWorld"

which looks very unexpected for me. For some reason, it does not use multi-line if there is a whitespace before \n. Is it expected behavior? How can I force the library to use multi-line anyway? (I have quite large jsons which can not be modified which is serialized in a single line, but should be serialized in multi-line)

got the same issue, so I split the source string by "\n", and then use strings.TrimRight(line, " ").