| 1 | # YAML support for the Go language |
| 2 | |
| 3 | [](https://pkg.go.dev/github.com/goccy/go-yaml) |
| 4 |  |
| 5 | [](https://codecov.io/gh/goccy/go-yaml) |
| 6 | [](https://goreportcard.com/report/github.com/goccy/go-yaml) |
| 7 | |
| 8 | <img width="300px" src="https://user-images.githubusercontent.com/209884/67159116-64d94b80-f37b-11e9-9b28-f8379636a43c.png"></img> |
| 9 | |
| 10 | ## This library has **NO** relation to the go-yaml/yaml library |
| 11 | |
| 12 | > [!IMPORTANT] |
| 13 | > This library is developed from scratch to replace [`go-yaml/yaml`](https://github.com/go-yaml/yaml). |
| 14 | > If you're looking for a better YAML library, this one should be helpful. |
| 15 | |
| 16 | # Why a new library? |
| 17 | |
| 18 | As of this writing, there already exists a de facto standard library for YAML processing for Go: [https://github.com/go-yaml/yaml](https://github.com/go-yaml/yaml). However, we believe that a new YAML library is necessary for the following reasons: |
| 19 | |
| 20 | - Not actively maintained |
| 21 | - `go-yaml/yaml` has ported the libyaml written in C to Go, so the source code is not written in Go style |
| 22 | - There is a lot of content that cannot be parsed |
| 23 | - YAML is often used for configuration, and it is common to include validation along with it. However, the errors in `go-yaml/yaml` are not intuitive, and it is difficult to provide meaningful validation errors |
| 24 | - When creating tools that use YAML, there are cases where reversible transformation of YAML is required. However, to perform reversible transformations of content that includes Comments or Anchors/Aliases, manipulating the AST is the only option |
| 25 | - Non-intuitive [Marshaler](https://pkg.go.dev/gopkg.in/yaml.v3#Marshaler) / [Unmarshaler](https://pkg.go.dev/gopkg.in/yaml.v3#Unmarshaler) |
| 26 | |
| 27 | By the way, libraries such as [ghodss/yaml](https://github.com/ghodss/yaml) and [sigs.k8s.io/yaml](https://github.com/kubernetes-sigs/yaml) also depend on go-yaml/yaml, so if you are using these libraries, the same issues apply: they cannot parse things that go-yaml/yaml cannot parse, and they inherit many of the problems that go-yaml/yaml has. |
| 28 | |
| 29 | # Features |
| 30 | |
| 31 | - No dependencies |
| 32 | - A better parser than `go-yaml/yaml`. |
| 33 | - [Support recursive processing](https://github.com/apple/device-management/blob/release/docs/schema.yaml) |
| 34 | - Higher coverage in the [YAML Test Suite](https://github.com/yaml/yaml-test-suite?tab=readme-ov-file) |
| 35 | - YAML Test Suite consists of 402 cases in total, of which `gopkg.in/yaml.v3` passes `295`. In addition to passing all those test cases, `goccy/go-yaml` successfully passes nearly 60 additional test cases ( 2024/12/15 ) |
| 36 | - The test code is [here](https://github.com/goccy/go-yaml/blob/master/yaml_test_suite_test.go#L77) |
| 37 | - Ease and sustainability of maintenance |
| 38 | - The main maintainer is [@goccy](https://github.com/goccy), but we are also building a system to develop as a team with trusted developers |
| 39 | - Since it is written from scratch, the code is easy to read for Gophers |
| 40 | - An API structure that allows the use of not only `Encoder`/`Decoder` but also `Tokenizer` and `Parser` functionalities. |
| 41 | - [lexer.Tokenize](https://pkg.go.dev/github.com/goccy/[email protected]/lexer#Tokenize) |
| 42 | - [parser.Parse](https://pkg.go.dev/github.com/goccy/[email protected]/parser#Parse) |
| 43 | - Filtering, replacing, and merging YAML content using YAML Path |
| 44 | - Reversible transformation without using the AST for YAML that includes Anchors, Aliases, and Comments |
| 45 | - Customize the Marshal/Unmarshal behavior for primitive types and third-party library types ([RegisterCustomMarshaler](https://pkg.go.dev/github.com/goccy/go-yaml#RegisterCustomMarshaler), [RegisterCustomUnmarshaler](https://pkg.go.dev/github.com/goccy/go-yaml#RegisterCustomUnmarshaler)) |
| 46 | - Respects `encoding/json` behavior |
| 47 | - 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. |
| 48 | - [json.Marshaler](https://pkg.go.dev/encoding/json#Marshaler) style [marshaler](https://pkg.go.dev/github.com/goccy/go-yaml#BytesMarshaler) |
| 49 | - [json.Unmarshaler](https://pkg.go.dev/encoding/json#Unmarshaler) style [unmarshaler](https://pkg.go.dev/github.com/goccy/go-yaml#BytesUnmarshaler) |
| 50 | - Options for using `MarshalJSON` and `UnmarshalJSON` ([UseJSONMarshaler](https://pkg.go.dev/github.com/goccy/go-yaml#UseJSONMarshaler), [UseJSONUnmarshaler](https://pkg.go.dev/github.com/goccy/go-yaml#UseJSONUnmarshaler)) |
| 51 | - Pretty format for error notifications |
| 52 | - Smart validation processing combined with [go-playground/validator](https://github.com/go-playground/validator) |
| 53 | - [example test code is here](https://github.com/goccy/go-yaml/blob/45889c98b0a0967240eb595a1bd6896e2f575106/testdata/validate_test.go#L12) |
| 54 | - Allow referencing elements declared in another file via anchors |
| 55 | |
| 56 | # Users |
| 57 | |
| 58 | The repositories that use goccy/go-yaml are listed here. |
| 59 | |
| 60 | - https://github.com/goccy/go-yaml/wiki/Users |
| 61 | |
| 62 | The source data is [here](https://github.com/goccy/go-yaml/network/dependents). |
| 63 | It is already being used in many repositories. Now it's your turn 😄 |
| 64 | |
| 65 | # Playground |
| 66 | |
| 67 | The Playground visualizes how go-yaml processes YAML text. Use it to assist with your debugging or issue reporting. |
| 68 | |
| 69 | https://goccy.github.io/go-yaml |
| 70 | |
| 71 | # Installation |
| 72 | |
| 73 | ```sh |
| 74 | go get github.com/goccy/go-yaml |
| 75 | ``` |
| 76 | |
| 77 | # Synopsis |
| 78 | |
| 79 | ## 1. Simple Encode/Decode |
| 80 | |
| 81 | Has an interface like `go-yaml/yaml` using `reflect` |
| 82 | |
| 83 | ```go |
| 84 | var v struct { |
| 85 | A int |
| 86 | B string |
| 87 | } |
| 88 | v.A = 1 |
| 89 | v.B = "hello" |
| 90 | bytes, err := yaml.Marshal(v) |
| 91 | if err != nil { |
| 92 | //... |
| 93 | } |
| 94 | fmt.Println(string(bytes)) // "a: 1\nb: hello\n" |
| 95 | ``` |
| 96 | |
| 97 | ```go |
| 98 | yml := ` |
| 99 | %YAML 1.2 |
| 100 | --- |
| 101 | a: 1 |
| 102 | b: c |
| 103 | ` |
| 104 | var v struct { |
| 105 | A int |
| 106 | B string |
| 107 | } |
| 108 | if err := yaml.Unmarshal([]byte(yml), &v); err != nil { |
| 109 | //... |
| 110 | } |
| 111 | ``` |
| 112 | |
| 113 | To control marshal/unmarshal behavior, you can use the `yaml` tag. |
| 114 | |
| 115 | ```go |
| 116 | yml := `--- |
| 117 | foo: 1 |
| 118 | bar: c |
| 119 | ` |
| 120 | var v struct { |
| 121 | A int `yaml:"foo"` |
| 122 | B string `yaml:"bar"` |
| 123 | } |
| 124 | if err := yaml.Unmarshal([]byte(yml), &v); err != nil { |
| 125 | //... |
| 126 | } |
| 127 | ``` |
| 128 | |
| 129 | For convenience, we also accept the `json` tag. Note that not all options from |
| 130 | the `json` tag will have significance when parsing YAML documents. If both |
| 131 | tags exist, `yaml` tag will take precedence. |
| 132 | |
| 133 | ```go |
| 134 | yml := `--- |
| 135 | foo: 1 |
| 136 | bar: c |
| 137 | ` |
| 138 | var v struct { |
| 139 | A int `json:"foo"` |
| 140 | B string `json:"bar"` |
| 141 | } |
| 142 | if err := yaml.Unmarshal([]byte(yml), &v); err != nil { |
| 143 | //... |
| 144 | } |
| 145 | ``` |
| 146 | |
| 147 | For custom marshal/unmarshaling, implement either `Bytes` or `Interface` variant of marshaler/unmarshaler. The difference is that while `BytesMarshaler`/`BytesUnmarshaler` behaves like [`encoding/json`](https://pkg.go.dev/encoding/json) and `InterfaceMarshaler`/`InterfaceUnmarshaler` behaves like [`gopkg.in/yaml.v2`](https://pkg.go.dev/gopkg.in/yaml.v2). |
| 148 | |
| 149 | Semantically both are the same, but they differ in performance. Because indentation matters 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. |
| 150 | |
| 151 | If you are repeatedly marshaling complex objects, the latter is always better |
| 152 | performance wise. But if you are, for example, just providing a choice between |
| 153 | a config file format that is read only once, the former is probably easier to |
| 154 | code. |
| 155 | |
| 156 | ## 2. Reference elements declared in another file |
| 157 | |
| 158 | `testdata` directory contains `anchor.yml` file: |
| 159 | |
| 160 | ```shell |
| 161 | ├── testdata |
| 162 |   └── anchor.yml |
| 163 | ``` |
| 164 | |
| 165 | And `anchor.yml` is defined as follows: |
| 166 | |
| 167 | ```yaml |
| 168 | a: &a |
| 169 | b: 1 |
| 170 | c: hello |
| 171 | ``` |
| 172 | |
| 173 | Then, if `yaml.ReferenceDirs("testdata")` option is passed to `yaml.Decoder`, |
| 174 | `Decoder` tries to find the anchor definition from YAML files the under `testdata` directory. |
| 175 | |
| 176 | ```go |
| 177 | buf := bytes.NewBufferString("a: *a\n") |
| 178 | dec := yaml.NewDecoder(buf, yaml.ReferenceDirs("testdata")) |
| 179 | var v struct { |
| 180 | A struct { |
| 181 | B int |
| 182 | C string |
| 183 | } |
| 184 | } |
| 185 | if err := dec.Decode(&v); err != nil { |
| 186 | //... |
| 187 | } |
| 188 | fmt.Printf("%+v\n", v) // {A:{B:1 C:hello}} |
| 189 | ``` |
| 190 | |
| 191 | ## 3. Encode with `Anchor` and `Alias` |
| 192 | |
| 193 | ### 3.1. Explicitly declared `Anchor` name and `Alias` name |
| 194 | |
| 195 | If you want to use `anchor`, you can define it as a struct tag. |
| 196 | If the value specified for an anchor is a pointer type and the same address as the pointer is found, the value is automatically set to alias. |
| 197 | If an explicit alias name is specified, an error is raised if its value is different from the value specified in the anchor. |
| 198 | |
| 199 | ```go |
| 200 | type T struct { |
| 201 | A int |
| 202 | B string |
| 203 | } |
| 204 | var v struct { |
| 205 | C *T `yaml:"c,anchor=x"` |
| 206 | D *T `yaml:"d,alias=x"` |
| 207 | } |
| 208 | v.C = &T{A: 1, B: "hello"} |
| 209 | v.D = v.C |
| 210 | bytes, err := yaml.Marshal(v) |
| 211 | if err != nil { |
| 212 | panic(err) |
| 213 | } |
| 214 | fmt.Println(string(bytes)) |
| 215 | /* |
| 216 | c: &x |
| 217 | a: 1 |
| 218 | b: hello |
| 219 | d: *x |
| 220 | */ |
| 221 | ``` |
| 222 | |
| 223 | ### 3.2. Implicitly declared `Anchor` and `Alias` names |
| 224 | |
| 225 | If you do not explicitly declare the anchor name, the default behavior is to |
| 226 | use the equivalent of `strings.ToLower($FieldName)` as the name of the anchor. |
| 227 | If the value specified for an anchor is a pointer type and the same address as the pointer is found, the value is automatically set to alias. |
| 228 | |
| 229 | ```go |
| 230 | type T struct { |
| 231 | I int |
| 232 | S string |
| 233 | } |
| 234 | var v struct { |
| 235 | A *T `yaml:"a,anchor"` |
| 236 | B *T `yaml:"b,anchor"` |
| 237 | C *T `yaml:"c"` |
| 238 | D *T `yaml:"d"` |
| 239 | } |
| 240 | v.A = &T{I: 1, S: "hello"} |
| 241 | v.B = &T{I: 2, S: "world"} |
| 242 | v.C = v.A // C has same pointer address to A |
| 243 | v.D = v.B // D has same pointer address to B |
| 244 | bytes, err := yaml.Marshal(v) |
| 245 | if err != nil { |
| 246 | //... |
| 247 | } |
| 248 | fmt.Println(string(bytes)) |
| 249 | /* |
| 250 | a: &a |
| 251 | i: 1 |
| 252 | s: hello |
| 253 | b: &b |
| 254 | i: 2 |
| 255 | s: world |
| 256 | c: *a |
| 257 | d: *b |
| 258 | */ |
| 259 | ``` |
| 260 | |
| 261 | ### 3.3 MergeKey and Alias |
| 262 | |
| 263 | Merge key and alias ( `<<: *alias` ) can be used by embedding a structure with the `inline,alias` tag. |
| 264 | |
| 265 | ```go |
| 266 | type Person struct { |
| 267 | *Person `yaml:",omitempty,inline,alias"` // embed Person type for default value |
| 268 | Name string `yaml:",omitempty"` |
| 269 | Age int `yaml:",omitempty"` |
| 270 | } |
| 271 | defaultPerson := &Person{ |
| 272 | Name: "John Smith", |
| 273 | Age: 20, |
| 274 | } |
| 275 | people := []*Person{ |
| 276 | { |
| 277 | Person: defaultPerson, // assign default value |
| 278 | Name: "Ken", // override Name property |
| 279 | Age: 10, // override Age property |
| 280 | }, |
| 281 | { |
| 282 | Person: defaultPerson, // assign default value only |
| 283 | }, |
| 284 | } |
| 285 | var doc struct { |
| 286 | Default *Person `yaml:"default,anchor"` |
| 287 | People []*Person `yaml:"people"` |
| 288 | } |
| 289 | doc.Default = defaultPerson |
| 290 | doc.People = people |
| 291 | bytes, err := yaml.Marshal(doc) |
| 292 | if err != nil { |
| 293 | //... |
| 294 | } |
| 295 | fmt.Println(string(bytes)) |
| 296 | /* |
| 297 | default: &default |
| 298 | name: John Smith |
| 299 | age: 20 |
| 300 | people: |
| 301 | - <<: *default |
| 302 | name: Ken |
| 303 | age: 10 |
| 304 | - <<: *default |
| 305 | */ |
| 306 | ``` |
| 307 | |
| 308 | ## 4. Pretty Formatted Errors |
| 309 | |
| 310 | Error values produced during parsing have two extra features over regular |
| 311 | error values. |
| 312 | |
| 313 | First, by default, they contain extra information on the location of the error |
| 314 | from the source YAML document, to make it easier to find the error location. |
| 315 | |
| 316 | Second, the error messages can optionally be colorized. |
| 317 | |
| 318 | If you would like to control exactly how the output looks like, consider |
| 319 | using `yaml.FormatError`, which accepts two boolean values to |
| 320 | control turning these features on or off. |
| 321 | |
| 322 | <img src="https://user-images.githubusercontent.com/209884/67358124-587f0980-f59a-11e9-96fc-7205aab77695.png"></img> |
| 323 | |
| 324 | ## 5. Use YAMLPath |
| 325 | |
| 326 | ```go |
| 327 | yml := ` |
| 328 | store: |
| 329 | book: |
| 330 | - author: john |
| 331 | price: 10 |
| 332 | - author: ken |
| 333 | price: 12 |
| 334 | bicycle: |
| 335 | color: red |
| 336 | price: 19.95 |
| 337 | ` |
| 338 | path, err := yaml.PathString("$.store.book[*].author") |
| 339 | if err != nil { |
| 340 | //... |
| 341 | } |
| 342 | var authors []string |
| 343 | if err := path.Read(strings.NewReader(yml), &authors); err != nil { |
| 344 | //... |
| 345 | } |
| 346 | fmt.Println(authors) |
| 347 | // [john ken] |
| 348 | ``` |
| 349 | |
| 350 | ### 5.1 Print customized error with YAML source code |
| 351 | |
| 352 | ```go |
| 353 | package main |
| 354 | |
| 355 | import ( |
| 356 | "fmt" |
| 357 | |
| 358 | "github.com/goccy/go-yaml" |
| 359 | ) |
| 360 | |
| 361 | func main() { |
| 362 | yml := ` |
| 363 | a: 1 |
| 364 | b: "hello" |
| 365 | ` |
| 366 | var v struct { |
| 367 | A int |
| 368 | B string |
| 369 | } |
| 370 | if err := yaml.Unmarshal([]byte(yml), &v); err != nil { |
| 371 | panic(err) |
| 372 | } |
| 373 | if v.A != 2 { |
| 374 | // output error with YAML source |
| 375 | path, err := yaml.PathString("$.a") |
| 376 | if err != nil { |
| 377 | panic(err) |
| 378 | } |
| 379 | source, err := path.AnnotateSource([]byte(yml), true) |
| 380 | if err != nil { |
| 381 | panic(err) |
| 382 | } |
| 383 | fmt.Printf("a value expected 2 but actual %d:\n%s\n", v.A, string(source)) |
| 384 | } |
| 385 | } |
| 386 | ``` |
| 387 | |
| 388 | output result is the following: |
| 389 | |
| 390 | <img src="https://user-images.githubusercontent.com/209884/84148813-7aca8680-aa9a-11ea-8fc9-37dece2ebdac.png"></img> |
| 391 | |
| 392 | |
| 393 | # Tools |
| 394 | |
| 395 | ## ycat |
| 396 | |
| 397 | print yaml file with color |
| 398 | |
| 399 | <img width="713" alt="ycat" src="https://user-images.githubusercontent.com/209884/66986084-19b00600-f0f9-11e9-9f0e-1f91eb072fe0.png"> |
| 400 | |
| 401 | ### Installation |
| 402 | |
| 403 | ```sh |
| 404 | git clone https://github.com/goccy/go-yaml.git |
| 405 | cd go-yaml/cmd/ycat && go install . |
| 406 | ``` |
| 407 | |
| 408 | |
| 409 | # For Developers |
| 410 | |
| 411 | > [!NOTE] |
| 412 | > In this project, we manage such test code under the `testdata` directory to avoid adding dependencies on libraries that are only needed for testing to the top `go.mod` file. Therefore, if you want to add test cases that use 3rd party libraries, please add the test code to the `testdata` directory. |
| 413 | |
| 414 | # Looking for Sponsors |
| 415 | |
| 416 | I'm looking for sponsors this library. This library is being developed as a personal project in my spare time. If you want a quick response or problem resolution when using this library in your project, please register as a [sponsor](https://github.com/sponsors/goccy). I will cooperate as much as possible. Of course, this library is developed as an MIT license, so you can use it freely for free. |
| 417 | |
| 418 | # License |
| 419 | |
| 420 | MIT |