go-yaml / yaml

YAML support for the Go language.
Other
6.87k stars 1.05k forks source link

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

Open 1755 opened 9 months ago

1755 commented 9 months ago

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)

kyouzzz commented 9 months ago

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

Larry-shuo commented 2 months ago

I have the same issue, there cannot be a space before "\n", but other character even "\t" before can be print rightly

lyingbug commented 4 days ago

same issue, is there any way to keep the multi-line style ?