| 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 |
# Why a new library? |
| 11 |
|
| 12 |
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 feel that some features are lacking, namely: |
| 13 |
|
| 14 |
- Pretty format for error notifications |
| 15 |
- Direct manipulation of YAML abstract syntax tree |
| 16 |
- Support for `Anchor` and `Alias` when marshaling |
| 17 |
- Allow referencing elements declared in another file via anchors |
| 18 |
|
| 19 |
# Features |
| 20 |
|
| 21 |
- Pretty format for error notifications |
| 22 |
- Supports `Scanner` or `Lexer` or `Parser` as public API |
| 23 |
- Supports `Anchor` and `Alias` to Marshaler |
| 24 |
- Allow referencing elements declared in another file via anchors |
| 25 |
- Extract value or AST by YAMLPath ( YAMLPath is like a JSONPath ) |
| 26 |
|
| 27 |
# Installation |
| 28 |
|
| 29 |
```sh |
| 30 |
go get -u github.com/goccy/go-yaml |
| 31 |
``` |
| 32 |
|
| 33 |
# Synopsis |
| 34 |
|
| 35 |
## 1. Simple Encode/Decode |
| 36 |
|
| 37 |
Has an interface like `go-yaml/yaml` using `reflect` |
| 38 |
|
| 39 |
```go |
| 40 |
var v struct { |
| 41 |
A int |
| 42 |
B string |
| 43 |
} |
| 44 |
v.A = 1 |
| 45 |
v.B = "hello" |
| 46 |
bytes, err := yaml.Marshal(v) |
| 47 |
if err != nil { |
| 48 |
//... |
| 49 |
} |
| 50 |
fmt.Println(string(bytes)) // "a: 1\nb: hello\n" |
| 51 |
``` |
| 52 |
|
| 53 |
```go |
| 54 |
yml := ` |
| 55 |
%YAML 1.2 |
| 56 |
--- |
| 57 |
a: 1 |
| 58 |
b: c |
| 59 |
` |
| 60 |
var v struct { |
| 61 |
A int |
| 62 |
B string |
| 63 |
} |
| 64 |
if err := yaml.Unmarshal([]byte(yml), &v); err != nil { |
| 65 |
//... |
| 66 |
} |
| 67 |
``` |
| 68 |
|
| 69 |
To control marshal/unmarshal behavior, you can use the `yaml` tag. |
| 70 |
|
| 71 |
```go |
| 72 |
yml := `--- |
| 73 |
foo: 1 |
| 74 |
bar: c |
| 75 |
` |
| 76 |
var v struct { |
| 77 |
A int `yaml:"foo"` |
| 78 |
B string `yaml:"bar"` |
| 79 |
} |
| 80 |
if err := yaml.Unmarshal([]byte(yml), &v); err != nil { |
| 81 |
//... |
| 82 |
} |
| 83 |
``` |
| 84 |
|
| 85 |
For convenience, we also accept the `json` tag. Note that not all options from |
| 86 |
the `json` tag will have significance when parsing YAML documents. If both |
| 87 |
tags exist, `yaml` tag will take precedence. |
| 88 |
|
| 89 |
```go |
| 90 |
yml := `--- |
| 91 |
foo: 1 |
| 92 |
bar: c |
| 93 |
` |
| 94 |
var v struct { |
| 95 |
A int `json:"foo"` |
| 96 |
B string `json:"bar"` |
| 97 |
} |
| 98 |
if err := yaml.Unmarshal([]byte(yml), &v); err != nil { |
| 99 |
//... |
| 100 |
} |
| 101 |
``` |
| 102 |
|
| 103 |
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). |
| 104 |
|
| 105 |
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. |
| 106 |
|
| 107 |
If you are repeatedly marshaling complex objects, the latter is always better |
| 108 |
performance wise. But if you are, for example, just providing a choice between |
| 109 |
a config file format that is read only once, the former is probably easier to |
| 110 |
code. |
| 111 |
|
| 112 |
## 2. Reference elements declared in another file |
| 113 |
|
| 114 |
`testdata` directory contains `anchor.yml` file: |
| 115 |
|
| 116 |
```shell |
| 117 |
├── testdata |
| 118 |
└── anchor.yml |
| 119 |
``` |
| 120 |
|
| 121 |
And `anchor.yml` is defined as follows: |
| 122 |
|
| 123 |
```yaml |
| 124 |
a: &a |
| 125 |
b: 1 |
| 126 |
c: hello |
| 127 |
``` |
| 128 |
|
| 129 |
Then, if `yaml.ReferenceDirs("testdata")` option is passed to `yaml.Decoder`, |
| 130 |
`Decoder` tries to find the anchor definition from YAML files the under `testdata` directory. |
| 131 |
|
| 132 |
```go |
| 133 |
buf := bytes.NewBufferString("a: *a\n") |
| 134 |
dec := yaml.NewDecoder(buf, yaml.ReferenceDirs("testdata")) |
| 135 |
var v struct { |
| 136 |
A struct { |
| 137 |
B int |
| 138 |
C string |
| 139 |
} |
| 140 |
} |
| 141 |
if err := dec.Decode(&v); err != nil { |
| 142 |
//... |
| 143 |
} |
| 144 |
fmt.Printf("%+v\n", v) // {A:{B:1 C:hello}} |
| 145 |
``` |
| 146 |
|
| 147 |
## 3. Encode with `Anchor` and `Alias` |
| 148 |
|
| 149 |
### 3.1. Explicitly declared `Anchor` name and `Alias` name |
| 150 |
|
| 151 |
If you want to use `anchor` or `alias`, you can define it as a struct tag. |
| 152 |
|
| 153 |
```go |
| 154 |
type T struct { |
| 155 |
A int |
| 156 |
B string |
| 157 |
} |
| 158 |
var v struct { |
| 159 |
C *T `yaml:"c,anchor=x"` |
| 160 |
D *T `yaml:"d,alias=x"` |
| 161 |
} |
| 162 |
v.C = &T{A: 1, B: "hello"} |
| 163 |
v.D = v.C |
| 164 |
bytes, err := yaml.Marshal(v) |
| 165 |
if err != nil { |
| 166 |
panic(err) |
| 167 |
} |
| 168 |
fmt.Println(string(bytes)) |
| 169 |
/* |
| 170 |
c: &x |
| 171 |
a: 1 |
| 172 |
b: hello |
| 173 |
d: *x |
| 174 |
*/ |
| 175 |
``` |
| 176 |
|
| 177 |
### 3.2. Implicitly declared `Anchor` and `Alias` names |
| 178 |
|
| 179 |
If you do not explicitly declare the anchor name, the default behavior is to |
| 180 |
use the equivalent of `strings.ToLower($FieldName)` as the name of the anchor. |
| 181 |
|
| 182 |
If you do not explicitly declare the alias name AND the value is a pointer |
| 183 |
to another element, we look up the anchor name by finding out which anchor |
| 184 |
field the value is assigned to by looking up its pointer address. |
| 185 |
|
| 186 |
```go |
| 187 |
type T struct { |
| 188 |
I int |
| 189 |
S string |
| 190 |
} |
| 191 |
var v struct { |
| 192 |
A *T `yaml:"a,anchor"` |
| 193 |
B *T `yaml:"b,anchor"` |
| 194 |
C *T `yaml:"c,alias"` |
| 195 |
D *T `yaml:"d,alias"` |
| 196 |
} |
| 197 |
v.A = &T{I: 1, S: "hello"} |
| 198 |
v.B = &T{I: 2, S: "world"} |
| 199 |
v.C = v.A // C has same pointer address to A |
| 200 |
v.D = v.B // D has same pointer address to B |
| 201 |
bytes, err := yaml.Marshal(v) |
| 202 |
if err != nil { |
| 203 |
//... |
| 204 |
} |
| 205 |
fmt.Println(string(bytes)) |
| 206 |
/* |
| 207 |
a: &a |
| 208 |
i: 1 |
| 209 |
s: hello |
| 210 |
b: &b |
| 211 |
i: 2 |
| 212 |
s: world |
| 213 |
c: *a |
| 214 |
d: *b |
| 215 |
*/ |
| 216 |
``` |
| 217 |
|
| 218 |
### 3.3 MergeKey and Alias |
| 219 |
|
| 220 |
Merge key and alias ( `<<: *alias` ) can be used by embedding a structure with the `inline,alias` tag. |
| 221 |
|
| 222 |
```go |
| 223 |
type Person struct { |
| 224 |
*Person `yaml:",omitempty,inline,alias"` // embed Person type for default value |
| 225 |
Name string `yaml:",omitempty"` |
| 226 |
Age int `yaml:",omitempty"` |
| 227 |
} |
| 228 |
defaultPerson := &Person{ |
| 229 |
Name: "John Smith", |
| 230 |
Age: 20, |
| 231 |
} |
| 232 |
people := []*Person{ |
| 233 |
{ |
| 234 |
Person: defaultPerson, // assign default value |
| 235 |
Name: "Ken", // override Name property |
| 236 |
Age: 10, // override Age property |
| 237 |
}, |
| 238 |
{ |
| 239 |
Person: defaultPerson, // assign default value only |
| 240 |
}, |
| 241 |
} |
| 242 |
var doc struct { |
| 243 |
Default *Person `yaml:"default,anchor"` |
| 244 |
People []*Person `yaml:"people"` |
| 245 |
} |
| 246 |
doc.Default = defaultPerson |
| 247 |
doc.People = people |
| 248 |
bytes, err := yaml.Marshal(doc) |
| 249 |
if err != nil { |
| 250 |
//... |
| 251 |
} |
| 252 |
fmt.Println(string(bytes)) |
| 253 |
/* |
| 254 |
default: &default |
| 255 |
name: John Smith |
| 256 |
age: 20 |
| 257 |
people: |
| 258 |
- <<: *default |
| 259 |
name: Ken |
| 260 |
age: 10 |
| 261 |
- <<: *default |
| 262 |
*/ |
| 263 |
``` |
| 264 |
|
| 265 |
## 4. Pretty Formatted Errors |
| 266 |
|
| 267 |
Error values produced during parsing have two extra features over regular |
| 268 |
error values. |
| 269 |
|
| 270 |
First, by default, they contain extra information on the location of the error |
| 271 |
from the source YAML document, to make it easier to find the error location. |
| 272 |
|
| 273 |
Second, the error messages can optionally be colorized. |
| 274 |
|
| 275 |
If you would like to control exactly how the output looks like, consider |
| 276 |
using `yaml.FormatError`, which accepts two boolean values to |
| 277 |
control turning these features on or off. |
| 278 |
|
| 279 |
<img src="https://user-images.githubusercontent.com/209884/67358124-587f0980-f59a-11e9-96fc-7205aab77695.png"></img> |
| 280 |
|
| 281 |
## 5. Use YAMLPath |
| 282 |
|
| 283 |
```go |
| 284 |
yml := ` |
| 285 |
store: |
| 286 |
book: |
| 287 |
- author: john |
| 288 |
price: 10 |
| 289 |
- author: ken |
| 290 |
price: 12 |
| 291 |
bicycle: |
| 292 |
color: red |
| 293 |
price: 19.95 |
| 294 |
` |
| 295 |
path, err := yaml.PathString("$.store.book[*].author") |
| 296 |
if err != nil { |
| 297 |
//... |
| 298 |
} |
| 299 |
var authors []string |
| 300 |
if err := path.Read(strings.NewReader(yml), &authors); err != nil { |
| 301 |
//... |
| 302 |
} |
| 303 |
fmt.Println(authors) |
| 304 |
// [john ken] |
| 305 |
``` |
| 306 |
|
| 307 |
### 5.1 Print customized error with YAML source code |
| 308 |
|
| 309 |
```go |
| 310 |
package main |
| 311 |
|
| 312 |
import ( |
| 313 |
"fmt" |
| 314 |
|
| 315 |
"github.com/goccy/go-yaml" |
| 316 |
) |
| 317 |
|
| 318 |
func main() { |
| 319 |
yml := ` |
| 320 |
a: 1 |
| 321 |
b: "hello" |
| 322 |
` |
| 323 |
var v struct { |
| 324 |
A int |
| 325 |
B string |
| 326 |
} |
| 327 |
if err := yaml.Unmarshal([]byte(yml), &v); err != nil { |
| 328 |
panic(err) |
| 329 |
} |
| 330 |
if v.A != 2 { |
| 331 |
// output error with YAML source |
| 332 |
path, err := yaml.PathString("$.a") |
| 333 |
if err != nil { |
| 334 |
panic(err) |
| 335 |
} |
| 336 |
source, err := path.AnnotateSource([]byte(yml), true) |
| 337 |
if err != nil { |
| 338 |
panic(err) |
| 339 |
} |
| 340 |
fmt.Printf("a value expected 2 but actual %d:\n%s\n", v.A, string(source)) |
| 341 |
} |
| 342 |
} |
| 343 |
``` |
| 344 |
|
| 345 |
output result is the following: |
| 346 |
|
| 347 |
<img src="https://user-images.githubusercontent.com/209884/84148813-7aca8680-aa9a-11ea-8fc9-37dece2ebdac.png"></img> |
| 348 |
|
| 349 |
|
| 350 |
# Tools |
| 351 |
|
| 352 |
## ycat |
| 353 |
|
| 354 |
print yaml file with color |
| 355 |
|
| 356 |
<img width="713" alt="ycat" src="https://user-images.githubusercontent.com/209884/66986084-19b00600-f0f9-11e9-9f0e-1f91eb072fe0.png"> |
| 357 |
|
| 358 |
### Installation |
| 359 |
|
| 360 |
```sh |
| 361 |
go install github.com/goccy/go-yaml/cmd/ycat@latest |
| 362 |
``` |
| 363 |
|
| 364 |
# Looking for Sponsors |
| 365 |
|
| 366 |
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. |
| 367 |
|
| 368 |
# License |
| 369 |
|
| 370 |
MIT |