Quantcast
Channel: Magnus K Karlsson
Viewing all articles
Browse latest Browse all 526

Introduction to YAML

$
0
0

Introduction

The YAML format has grown in popularity and is used for example in Kubernetes and Ansible.

Comparison XML, JSON and YAML

XMLJSONYAML

<Servers>
<Server>
<id>12345</id>
<name>My Web Server</name>
<status>ACTIVE</status>
</Server>
</Servers>

{
"Servers": [
{
"id": "12345",
"name": "My Web Server",
"status": "ACTIVE"
}
]
}

Servers:
- id: 1234
name: My Web Server
status: ACTIVE

Tools for validating JSON

There are numerous tools out that for JSON, one for Linux and Bash is jq - a lightweight and flexible command-line JSON processor.


$ sudo yum install jq

$ cat servers.json | jq '.Servers[0].id'
"12345"

Tools for validating YAML

And a Linux and Bash tool for YAML is yq


$ sudo yum install python3 python3-pip
$ sudo pip3 install yq

$ cat servers.yaml | yq '.'
{
"Servers": [
{
"id": 1234,
"name": "My Web Server",
"status": "ACTIVE"
}
]
}

YAML Data Types

WARNING: YAML is not structured in the same sense as XML, JSON, XHTML, etc. It uses spaces (and not tabs and do not mix space and tabs) as seperator. So pay extra attention to how many spaces you use.

Key Value Pair


Fruit: Orange
Vegetable: Lettuce
Liquid: Wine

$ cat key_value_pair.yaml | yq '.'
{
"Fruit": "Orange",
"Vegetable": "Lettuce",
"Liquid": "Wine"
}

List (Array)


Fruits:
- Orange
- Apple
- Banana

Vegetables:
- Carrot
- Tomatoes
- Onion

$ cat array_list.yaml | yq '.'
{
"Fruits": [
"Orange",
"Apple",
"Banana"
],
"Vegetables": [
"Carrot",
"Tomatoes",
"Onion"
]
}

Dictionary (Map)


Banana:
Calories: 105
Fat: 0.4 g
Carbs: 31 g

Grapes:
Calories: 27
Fat: 0.7 g
Carbs: 56 g

$ cat dictionary_map.yaml | yq '.'
{
"Banana": {
"Calories": 105,
"Fat": "0.4 g",
"Carbs": "31 g"
},
"Grapes": {
"Calories": 27,
"Fat": "0.7 g",
"Carbs": "56 g"
}
}

More Advanced Examples. List of Dictionary (Array of Map)


Fruits:
- Orange:
Calories: 105
Fat: 0.4 g
Carbs: 31 g
- Apple:
Calories: 27
Fat: 0.7 g
Carbs: 56 g

$ cat array_list_of_dictionary_map.yaml | yq '.'

$ cat array_list_of_dictionary_map.yaml | yq '.Fruits[1]'
{
"Apple": {
"Calories": 27,
"Fat": "0.7 g",
"Carbs": "56 g"
}
}

Differences between List and Dictionary

Dictionary - Unordered

List - Ordered


Viewing all articles
Browse latest Browse all 526

Trending Articles