go-yaml icon indicating copy to clipboard operation
go-yaml copied to clipboard

Single quoted string output is not consistent with input

Open michaellzc opened this issue 3 years ago • 4 comments

Thanks for the amazing library.

Description

If the input yaml file contains single-quoted string, they are converted to double-quoted string after marshalling. Is this expected behaviour?

https://play.golang.org/p/JLbpVImLy2K

struct {
	A string `yaml:"username"`
	B string `yaml:"password"`
}

Input for unmarshal

username: '{{ requiredEnv "USERNAME" }}'
password: '{{ requiredEnv "PASSWORD" }}'

Output of marshal

username: "{{ requiredEnv \"USERNAME\" }}"
password: "{{ requiredEnv \"PASSWORD\" }}"

michaellzc avatar Oct 11 '20 00:10 michaellzc

First, go-yaml outputs double quotes by default. If once you decode by yaml.Unmarshal to string value, there is no way to know whether the original string was a single quote or a double quote. Therefore, this behavior is intended.

If you want to avoid this behavior, you can do so by using ast.Node API.

goccy avatar Oct 30 '20 02:10 goccy

Would it be possible for this to be an encoding option?

mcdee avatar Oct 30 '20 17:10 mcdee

I think it is good to offer it as an option. For example

package yaml

type QuoteStyle int

const (
  SingleQuoteStyle QuoteStyle = iota
  DoubleQuoteStyle 
)

func QuoteForEscape(style QuoteStyle) EncodeOption

goccy avatar Nov 13 '20 04:11 goccy

This would be a great addition for me, thanks!

mcdee avatar Nov 13 '20 08:11 mcdee