Golang how to avoid double quoted on key "on" when marshaling struct to yaml


I have a simple struct such as:

type Foo struct {
    On string `yaml:"on"`

And want to marshal this struct into YAML string in either way

Always get the same result with double-quote on key "on"

"on": hello

How can I avoid this? Following is the result I want

on: hello

The version of go is go1.17.2 darwin/amd64


That would be invalid YAML1.1 (or at least confusing) because on is keyword interpreted as boolean value true (see YAML1.1 spec).

As per go-yaml documentation:

The yaml package supports most of YAML 1.2, but preserves some behavior from 1.1 for backwards compatibility.

Specifically, as of v3 of the yaml package:

  • YAML 1.1 bools (yes/no, on/off) are supported as long as they are being decoded into a typed bool value. Otherwise they behave as a string. Booleans in YAML 1.2 are true/false only.

If you change yaml:"on" to anything else like yaml:"foo" key will not be quoted.

type T struct {
    On  string `yaml:"on"`
    Foo string `yaml:"foo"`

func main() {
    t := T{
        On:  "Hello",
        Foo: "world",

    b, _ := yaml.Marshal(&t)

// "on": hello
// foo: world

Answered By – blami

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.