Skip to content

yaml: errorprone with []byte #42

@ainar-g

Description

@ainar-g

Consider the code:

package main

import (
	"encoding/json"
	"fmt"
	"strings"

	"gopkg.in/yaml.v2"
)

type T struct {
	B []byte `json:"b" yaml:"b"`
}

const jsonData = `{"b":"aGVsbG8K"}`

const yamlData = `b: aGVsbG8K`

func main() {
	var err error
	var t T

	err = json.NewDecoder(strings.NewReader(jsonData)).Decode(&t)
	fmt.Printf("%v %v\n", err, t)

	t = T{}
	err = yaml.NewDecoder(strings.NewReader(yamlData)).Decode(&t)
	fmt.Printf("%v %v\n", err, t)
}

Here, the programmer assumed that []byte fields in gopkg.in/yaml.v2 behave the same way as in encoding/json. But they don't:

<nil> {[104 101 108 108 111 10]}
yaml: unmarshal errors:
  line 1: cannot unmarshal !!str `aGVsbG8K` into []uint8 {[]}

It seems like you still can use []byte with that module, but only if you actually use a YAML array, which is probably not something most people want:

b:
- 104
- 101
- 108
- 108
- 111
- 10

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions