1 # YAML marshaling and unmarshaling support for Go
3 [![Build Status](https://travis-ci.org/ghodss/yaml.svg)](https://travis-ci.org/ghodss/yaml)
7 A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs.
9 In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/).
13 This package uses [go-yaml](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility).
17 **Caveat #1:** When using `yaml.Marshal` and `yaml.Unmarshal`, binary data should NOT be preceded with the `!!binary` YAML tag. If you do, go-yaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the `!!binary` tag and decode the base64 in your code (e.g. in the custom JSON methods `MarshalJSON` and `UnmarshalJSON`). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example:
21 exampleKey: !!binary gIGC
25 ... and decode the base64 data in your code.
28 **Caveat #2:** When using `YAMLToJSON` directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in `Unmarshal` as well since you can't unmarshal map keys anyways since struct fields can't be keys.
30 ## Installation and usage
35 $ go get github.com/ghodss/yaml
41 import "github.com/ghodss/yaml"
44 Usage is very similar to the JSON library:
52 "github.com/ghodss/yaml"
56 Name string `json:"name"` // Affects YAML field names too.
61 // Marshal a Person struct to YAML.
62 p := Person{"John", 30}
63 y, err := yaml.Marshal(p)
65 fmt.Printf("err: %v\n", err)
68 fmt.Println(string(y))
74 // Unmarshal the YAML back into a Person struct.
76 err = yaml.Unmarshal(y, &p2)
78 fmt.Printf("err: %v\n", err)
88 `yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available:
96 "github.com/ghodss/yaml"
100 j := []byte(`{"name": "John", "age": 30}`)
101 y, err := yaml.JSONToYAML(j)
103 fmt.Printf("err: %v\n", err)
106 fmt.Println(string(y))
111 j2, err := yaml.YAMLToJSON(y)
113 fmt.Printf("err: %v\n", err)
116 fmt.Println(string(j2))
118 {"age":30,"name":"John"}