go-yaml / yaml

YAML support for the Go language.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Untagged field names "y" and "n" marshalled with quotes, others not

TLINDEN opened this issue · comments

package main

import (
  "fmt"
  "image"
  "gopkg.in/yaml.v3"
)

func main() {
  p := image.Point{4, 5}
  bytetree, _ := yaml.Marshal(p)
  fmt.Println(string(bytetree))
}

prints:

x: 4
"y": 5

It doesn't matter if it is an upper or lower case y. The letters n and N are also affected.

That comes really unexpected. Looks like some strange interpretation of y as yes and n as no - but why the quotes?

best regards,
Tom

I don't thing this is a bug.
https://yaml.org/type/bool.html

I see.

I understand it for values, as in enable: yes which should become enable: true. But why would anyone do this with keys? Doesn't make any sense to me.

So now I have to add a function to my code to remove the quotes in such cases, because I use YAML only for pretty printing of arbitrary structs.

😠

I've seen a fair share of weird things people do in yaml. I do agree that keys shouldn't be treated as values. I haven't read up on the yaml spec to the fullest, so I'm not sure if this is "by spec" or not. I just stumbled upon your issue by "accident". Hope someone more well versed in the spec can chime in

It's worse than just adding quotes, it also removes keys from the struct:

	type Punkt struct {
		y, YES, yes int
	}

	po := Punkt{4, 6, 8}
	by, _ := yaml.Marshal(po)
	fmt.Println(string(by))
	
	fmt.Printf("Punkt: %#v", po)

Prints:

"yes": 6

Punkt: main.Punkt{y:4, YES:6, yes:8}
  1. YAML is a data serialization language. Mapping keys can be strings, numbers, null, booleans and even mappings or sequences as well. Not every language can implement this, but a boolean as a mapping key is totally valid in YAML, even if you don't see a use case for it
    2.. go-yaml implements YAML 1.1, where y and n are booleans. in YAML 1.2 the list of scalars that are recognized as booleans has been reduced drastically, along with some other changes. More and more YAML libraries are slowly picking this up, but it is still not very well known by users.

Thanks for the clarification. I already put a workaround into my module, since I am only using YAML as data dumper/visualization tool.