Skip to content

Commit

Permalink
Add documentation and example tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lestrrat committed Nov 14, 2019
1 parent 1dbf6f4 commit 45fd347
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 1 deletion.
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,40 @@ if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
}
```

To control marshal/unmarshal behavior, you can use the `yaml` tag

```go
yml := `---
foo: 1
bar: c
`
var v struct {
A int `yaml:"foo"`
B string `yaml:"bar"`
}
if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
...
}
```

For convenience, we also accept the `json` tag. Note that not all options from
the `json` tag will have significance when parsing YAML documents. If both
tags exist, `yaml` tag will take precedence.

```go
yml := `---
foo: 1
bar: c
`
var v struct {
A int `json:"foo"`
B string `json:"bar"`
}
if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
...
}
```

For custom marshal/unmarshaling, implement one of Bytes or Interface Marshaler/Unmarshaler. The difference is that while BytesMarshaler/BytesUnmarshaler behave like `encoding.json`, InterfaceMarshaler/InterfaceUnmarshaler behave like `gopkg.in/yaml.v2`.

Semantically both are the same, but they differ in performance. Because indentation matter in YAML, you cannot simply accept a valid YAML fragment from a Marshaler, and expect it to work when it is attached to the parent container's serialized form. Therefore when we receive use the BytesMarshaler, which returns []byte, we must decode it once to figure out how to make it work in the given context. If you use the InterfaceMarshaler, we can skip the decoding.
Expand Down
43 changes: 42 additions & 1 deletion decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package yaml_test
import (
"bytes"
"fmt"
"log"
"math"
"reflect"
"strings"
Expand Down Expand Up @@ -1061,7 +1062,7 @@ a:

func TestDecoder_JSONTags(t *testing.T) {
var v struct {
A string `json:"a_json"` // no YAML tag
A string `json:"a_json"` // no YAML tag
B string `json:"b_json" yaml:"b_yaml"` // both tags
}

Expand All @@ -1082,3 +1083,43 @@ b_yaml: b_yaml_value
t.Fatalf("v.B should be `b_yaml_value`, got `%s`", v.B)
}
}

func Example_YAMLTags() {
yml := `---
foo: 1
bar: c
A: 2
B: d
`
var v struct {
A int `yaml:"foo" json:"A"`
B string `yaml:"bar" json:"B"`
}
if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
log.Fatal(err)
}
fmt.Println(v.A)
fmt.Println(v.B)
// OUTPUT:
// 1
// c
}

func Example_JSONTags() {
yml := `---
foo: 1
bar: c
`
var v struct {
A int `json:"foo"`
B string `json:"bar"`
}
if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
log.Fatal(err)
}
fmt.Println(v.A)
fmt.Println(v.B)
// OUTPUT:
// 1
// c
}

0 comments on commit 45fd347

Please sign in to comment.