Skip to main content

YAML

YAML is a data-serialization language commonly used in config files. Notable examples in Coko apps would be docker-compose and gitlab-ci files. The file extension for YAML files is yml.

info

You can convert yml files to json with an online tool like this one. This can be useful if you are unsure of a file's YAML structure and want to see it in a more familiar format.

Basics

Keys

name: John

Nested keys

address:
street: Manhattan Dr.
number: 12

Arrays

fruit:
- orange
- apple
- pear

# alternative syntax
exoticFruit: [mango, pineapple]

Arrays of objects

food:
- name: sardines
expired: false
- name: bread
expired: true

Comments

# Use the # symbol to add comments
info

Quotes around strings are valid, but optional.

Now let's bring all of the above together and pass it to our json converter to see what it looks like:

In YAML:

name: John
address:
street: Manhattan Dr.
number: 12

fruit:
- orange
- apple
- pear
exoticFruit: [mango, pineapple]

food:
- name: sardines
expired: false
- name: bread
expired: true

And in json:

{
"name": "John",
"address": {
"street": "Manhattan Dr.",
"number": 12
},
"fruit": ["orange", "apple", "pear"],
"exoticFruit": ["mango", "pineapple"],
"food": [
{
"name": "sardines",
"expired": false
},
{
"name": "bread",
"expired": true
}
]
}

Anchors

Anchors allow us to reference other values within the file, thereby reducing duplication and keeping things clean.

Use & to define an alias and * to reference it:

person:
name: &name John
hobbies:
- lacrosse
- polo
self: *name

If we run this through the json converter, we'll notice that self has the same value as name:

{
"person": {
"name": "John",
"hobbies": ["lacrosse", "polo"],
"self": "John"
}
}

A more useful scenario would be to reference a bigger object that is commmon between other objects to reduce duplication.

You can insert all the values defined in the alias to the new object:

base_person: &base
city: Lisbon
country: Portugal

person:
# Use the << syntax to insert all the values
<<: *base
name: John
hobbies:
- lacrosse
- polo

In json:

{
"person": {
"city": "Lisbon",
"country": "Portugal",
"name": "John",
"hobbies": ["lacrosse", "polo"],
"self": "John"
}
}

Or you can store them in a new key:

base_person: &base
city: Lisbon
country: Portugal

person:
countryInfo: *base
name: John
hobbies:
- lacrosse
- polo

In json:

{
"person": {
"countryInfo": {
"city": "Lisbon",
"country": "Portugal"
},
"name": "John",
"hobbies": ["lacrosse", "polo"]
}
}

Multi-line strings

There are cases where you want to add a string as a value, but preserve its newlines (eg. if the value is a script in a gitlab-ci.yml file). To achieve this we can use the | operator.

my_multiline_value: |
console.log("this is one line")
console.log("this is another line")

Resources

YAML anchors
https://support.atlassian.com/bitbucket-cloud/docs/yaml-anchors/

YAML multi-line strings
https://yaml-multiline.info/