YAML Cheatsheet
Multiline Strings
Indented text that follows should be interpreted as a multi-line scalar value
- default: newlines become spaces.
|
: preserves newlines.|+
: keep extra newlines after the block.|-
: remove extra newlines after block.
>
: newlines are converted to spaces.>+
: keep extra newlines after the block.>-
: remove extra newlines after block.
$ cat <<EOF | yq '.content'
content:
a b
c d e
f g
EOF
# a b c d e
# f g
$ cat <<EOF | yq '.content'
content: |
a b
c d e
f g
EOF
# a b
# c d e
#
# f g
#
$ cat <<EOF | yq '.content'
content: |+
a b
c d e
f g
EOF
# a b
# c d e
#
# f g
#
$ cat <<EOF | yq '.content'
content: |-
a b
c d e
f g
EOF
# a b
# c d e
#
# f g
$ cat <<EOF | yq '.content'
content: >
a b
c d e
f g
EOF
# a b c d e
# f g
#
$ cat <<EOF | yq '.content'
content: >-
a b
c d e
f g
EOF
# a b c d e
# f g
Interactive examples: https://yaml-multiline.info/
Single-quoted vs Double-quoted
- single: don't escape (e.g.
\n
,\"
has no effects). To escape single quotes:''
. - double: escapes work. To escape double quotes:
\"
.
By Language
Go
JSON is included in Go's standard library, but not YAML. There are a few third-party options:
- go-yaml: https://github.com/go-yaml/yaml
- inconsistent with how JSON is handled in golang.
- go-yaml works virtually identically to the JSON library, except instead of JSON struct tags, you use YAML struct tags, and instead of
MarshalJSON
andUnmarshalJSON
, you useMarshalYAML
andUnmarshalYAML
.
- sigs.k8s.io/yaml: https://pkg.go.dev/sigs.k8s.io/yaml
- wrapping go-yaml
- first converts YAML to JSON using go-yaml and then uses
json.Marshal
andjson.Unmarshal
to convert to or from thestruct
. - Benefits: reuse JSON struct tags as well as the custom JSON methods
MarshalJSON
andUnmarshalJSON
unlike go-yaml. - As the name suggests: used in k8s.
go-yaml
Install gopkg.in/yaml.v3
:
$ go get gopkg.in/yaml.v3
import "gopkg.in/yaml.v3"
// Marshal
bytes, err := yaml.Marshal(&foo)
// Unmarshal
err := yaml.Unmarshal(bytes, &foo)
k8s yaml
API:
func Marshal(o interface{}) ([]byte, error)
func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error
Import:
import "sigs.k8s.io/yaml"
Python
yaml
module can be used to easily read or write yaml files.
Install:
$ pip install yaml
In code:
>>> import yaml
# Read from file
>>> yaml.load(open("test.yml"))
# Write to File
>>> yaml.dump(obj)