en Introduction to YAML for beginners

Introduction to YAML for beginners

If you’re a developer creating APIs, you’ve probably encountered YAML, even if your primary serialization tool is JSON.

YAML has a unique and easy-to-use syntax, making it a useful language to add to your development arsenal.

Learn the basics of YAML.

Introduction to YAML for beginners
Introduction to YAML for beginners

Serializing data

If you want to send any data structure or object over a computer network (such as the Internet), you must convert it to a special format in order to read and store it. This process is commonly known as serialization and is very important on the web. A common use case for serialization is reading data from a database and transferring it over the web.

Some serialization formats include JSON, YAML, and XML.

This article describes YAML. At the end of the article, you will be able to become proficient with YAML and will have a clear overview about YAML.

What is YAML? What are the benefits of YAML?

YAML is a data serialization format that stands for “YAML ain’t Markup language.”

The main advantage of using YAML is readability and ease of writing. If you have configuration files that need to be human-readable, we recommend using YAML. YAML is not a complete replacement for JSON, as JSON and XML also have their roles. Still, learning YAML can be helpful.

Another advantage of YAML is that it supports a variety of data types such as cases, arrays, dictionaries, lists, and scalars. It has full support for the most popular languages ​​such as JavaScript, Python, Ruby, and Java.

YAML only supports spaces and is case sensitive as well as spaces. Tabs are not accepted worldwide. YAML files have a .yaml extension.

Introduction to YAML for beginners
Introduction to YAML for beginners

Basic YAML syntax

All YAML begins with --- , which indicates the beginning of the YAML file.

When creating an API, focus on a feature provided by YAML called mapping.

The following example shows an example mapping in YAML.

 ---
name: James
boy: yes
GPA: 3.41

The mapping syntax is key:value. (Note the spaces. Unlike JSON and XML, spaces are very important in YAML.

YAML also supports data types such as characters, strings, integers, and floating point values, as well as collections such as arrays and lists that are made up of primitive data types.

YAML data types

Take a look at the YAML example below.

 ---

MALE: FALSE

GPA: 3.61

ISSUES: NULL

NAME: “BIGYAN”

AGE: 16

The first data type is Boolean, which can have two values: true or false. GPA values ​​are floating point numbers. YAML also supports null data types, as in the case of Issues . The Name value is a string that must be enclosed in double or single quotes. YAML also supports multiline strings and single multiline strings for readability.

Multi-line and single-line strings

 ---

About: >

 Hello this is Ryan

 From Alabama and I like to

 Play soccer.

The <i>></i> symbol allows you to write a single line of text onto multiple lines. Although the sentence is multiple lines, it is actually a single line of explanation.

You can also have multiple line strings using | . Symbols such as allowed:

 About: |

 This is a multiline string

 And will be printed line wise.

list

Lists are very important in YAML.

An example list is shown below.

 ---

- apple

- banana

- mango

The mapping from scalar to list is shown below. This is very important for most configuration files.

 ---

Fruits:

 Apples

 Banana

 Guava 

Nesting is required to map a scalar to a list. You can also use multiple nested lists, as shown in the example below.

 Automobiles:

 Car:

     Hyundai

     Volkswagen

     Ford

Here, cars are nested within cars, and Hyundai is nested within cars. This is an example of multiple nesting. You can create multiple nests as needed.

 Subjects:

     Engineering:

       Mechanical engineering:

         Design and manufacture

         Automobile

         Control and Design

       Civil engineering:

         Structural engineering

         Hydropower

       Arts:

         Medieval

         Modern

         Painting

YAML also provides & and * symbols and references to anchors as anchors to avoid duplication. These are essential for configuration files in frameworks such as Ruby on Rails to keep YAML files small.

See example below

 <span class="hljs-attr">details:</span> <span class="hljs-meta">&details</span>
    <span class="hljs-attr">name:</span> <span class="hljs-string">"John"
</span>    age: 18
 profession: engineer

<< : * details

This is equivalent to:

 profession: engineer

name: "John"

age: 18 
Introduction to YAML for beginners
Introduction to YAML for beginners

YAML in Python

Python supports YAML, including several modules such as ruamel and pyyaml. First, start by installing pyyaml

pip install pyyaml

The tutorial creates a file named details.yaml .

 name: "john"

age:18

gender: male

Create another file named feed.yaml with the following content:

 sports:

 football
 basketball
 cricket
 baseball

---
countries:
 Brazil
 Lithuania
 Australia
 USA

First, let’s read the file details.yaml .

 import yaml

with open('details.yaml') as f:
    
    data = yaml.load(f, Loader=yaml.FullLoader)
    print(data)

When I run the file details.py I get the following output:

 $ python details.py
{'name': "john", 'age': 18, 'gender': male}
 import yaml

with open(r'feed.yaml') as file:
    # The FullLoader parameter handles the conversion from YAML
    # scalar values to Python the dictionary format
    fruits_list = yaml.load(file, Loader=yaml.FullLoader)

    print(fruits_list)
Introduction to YAML for beginners
Introduction to YAML for beginners

Write YAML to a file with Python

 import yaml

dict_file = [{'sports' : ['hockey', 'rugby', 'tennis', 'ping pong', 'football', 'badminton']},
{'countries' : ['Jamaica', 'England', 'Nepal', 'Netherlands', 'South Africa', 'Bolivia', 'Portugal']}]

with open(r'E:\data.yaml', 'w') as file: #create a new yaml file 
    data = yaml.dump(dict_file, file)
Introduction to YAML for beginners
Introduction to YAML for beginners

YAML implementation in Node.js

Node.js is a server-side processing language, and data serialization is very important in the development process.

For this tutorial, consider the following file example.yaml .

 name:John

age:18

Hobbies:

 Hobby1:Football

 Hobby2:BasketBall

 Hobby3:Hockey

Job:

-System administrator

-Programmer

There is an npm library called js-yaml that can be used with Node.js. First, let’s install the module

 npm install js-yaml

Then use js-yaml module inside your file.

 const yaml = require('js-yaml'); //initialize js-yaml
const fs   = require('fs'); //initialize filestream

try {
  const result = yaml.load(fs.readFileSync('example.yml', 'utf8'));
  console.log(result);
} catch (e) {
  console.log(e); //catch exception
}

conclusion

It is becoming increasingly common for modern programming frameworks and applications where data is stored or distributed to use YAML in their configuration files. YAML targets many of the same communication applications as Extensible Markup Language (XML), but has a minimal syntax that is intentionally different from XML.

YAML files can be created for fixed data structures using print commands that write both the data and certain YAML decorations. However, to dump diverse or complex hierarchical data, we recommend using a dedicated YAML emitter. Similarly, regular expressions make it easy to parse basic YAML files (such as key-value pairs).