go-yaml / yaml

YAML support for the Go language.
Other
6.84k stars 1.04k forks source link

Inconsistent behaviour when marshalling strings #986

Open eBerdnA opened 1 year ago

eBerdnA commented 1 year ago

I have the following input file.

title: "2023-08-23"
title2: "A title with a colon: inside"
title3: '2023-08-23'

Using the following code I get a slightly unexpected result. I use v3.0.1 and go1.20.2 darwin/arm64 for this.

rawYaml, _ := os.ReadFile("./input.yaml")
yamlMap := make(map[string]string)
yaml.Unmarshal(rawYaml, &yamlMap)

marschalled, _ := yaml.Marshal(yamlMap)
fmt.Println(string(marschalled))

The output is the following.

title: "2023-08-23"
title2: 'A title with a colon: inside'
title3: "2023-08-23"

My questions is, why is title still encapsulated in double quotes but title2 is only encapsulated with single quotes and title3 even gets switched over. For me this behaviour looks quite confusing and inconsistent.

schneefisch commented 8 months ago

In YAML, both single and double quotes denote strings. However, they have slightly different behaviors:

Regarding the behavior you're seeing, this discrepancy is due to how the gopkg.in/yaml.v3 package handles strings when marshalling YAML in Go. The YAML package outputs a valid YAML representation of a string, choosing the appropriate style (plain, single-quoted, or double-quoted) given the content of the string.

Here's a bit more specifics:

Both, single-quoted and double-quoted representations are valid YAML and equivalent in value.