preface

When using GitLab CI, yML file configuration is used, but what exactly is YML? I have no impression at all, so I want to learn about it

purpose

Learn yamL syntax and how to use it in Python

yaml

The word yamL was JB’s first encounter, when he was fiddling with gitlab CI, dealing with.gitlab-ci.yml files, and thus yamL; At first I thought it was phP-like stuff, but it turned out that some of it wasn’t written right, and that led to, what is YAMl? What does it do?

The official website link: http://yaml.org/

There is a sentence on the official website:



YAML is a special language for writing configuration files


Introduction to the

YAML was designed to make it easy for people to read and write. It is essentially a universal data serialization format; Data-centric organization of data using whitespace, indentation, and lines to make presentation more concise and readable; Its basic syntax rules are as follows:

  • Case sensitivity
  • Use indentation to indicate hierarchy
  • The Tab key is not allowed for indentation. Only Spaces are allowed.
  • The number of Spaces indented does not matter, as long as elements of the same rank are aligned to the left
  • Using # to indicate a comment is ignored by the parser from this character all the way to the end of the line.
  • Strings can be annotated without quotes

Three data structures

1) a collection of object key-value pairs, also known as mapping/hashes/dictionary. Colons (:) are used to represent key-value pairs. All key-value pairs with the same indentation belong to a map

# YAML {age:12,name:huang} # YAML {'age':18,'name':'jb'}Copy the code

A list of lines beginning with a conjunction line (-) forming an array

# YAML stands for -a - b - 12 or a line: # YAML stands for [a,b,c] # corresponds to Json stands for ['a','b',12]Copy the code

3) Scalar is the smallest unit with scalar data, which cannot be divided any more such as numeric type, string, date, string, etc.

Data structure nesting

1) Map Nested map

# YAML websites: YAML: yaml.org Ruby: Python: python.org Perl: use.perl.org { YAML: 'yaml.org', Ruby: 'ruby-lang.org', Python: 'python.org', Perl: 'use.perl.org' } }Copy the code

2) map nested list

{languages: ['Ruby', 'Perl', 'Python', 'c']}Copy the code

3) list nested list

# YAML said Ruby - Perl - Python -- - c - c + +, Java # corresponding Json representation [[' Ruby, 'Perl', 'Python], [' c', 'c + +', 'Java']]Copy the code

In addition, it can be displayed as follows:

# method 3 - [Ruby,Perl,Python] - [c, C ++, Java]Copy the code

4) List nested map

{id: 1, name: 'huang'}, {id: 2, name: 'liao'}Copy the code

Install the YAML module

pip install pyyaml
Copy the code

Write yamL files

Once installed, manually create a new YAML file:

name: jb
age: 18
spouse:
    name: jb2
    age: 19
children:
    - name: jb3
      age: 1
    - name: jb4
      age: 2
Copy the code

If you want to modify the content, what to do? Look at an example;

Import yaml f = open("jb.yaml") content = yaml.load(f) # print(" before :"+ STR (content)) content["age"] = 17 Content (" children ") [1] [" age "] = 18 print (" revised: "+ STR (content)) the result of the execution: modify before: {' name ':' jb ', 'age: 18,' spouse ': {" name" : 'jb2', 'age: 19}' children ': [{' name' : 'jb3', 'age: 1}, {' name' : 'jb4', 'age: 2}]} modified: {' name' : 'jb', 'age: 17, 'spouse': {'name': 'jb2', 'age': 19}, 'children': [{'name': 'jb3', 'age': 1}, {'name': 'jb4', 'age': 18}]}Copy the code

There’s the load method, which returns an object;

If you have several blocks of YAML documents, load_all() can be used to generate an iterator:

The data is changed to:

name: jb --- age: 18 spouse: name: jb2 age: 19 children: - name: jb3 age: 1 - name: jb4 age: Import yaml f = open("jb.yaml") content = yaml.load_all(f) for I in content: print(I) 'jb'} {'age': 18, 'spouse': {'name': 'jb2', 'age': 19}, 'children': [{'name': 'jb3', 'age': 1}, {'name': 'jb4', 'age': 2}}]Copy the code

Dump, which generates a Python object into a YAML document

import yaml aproject = {'name': 'jb', 'race': 'jb', 'traits': ['ONE_HAND', 'ONE_EYE']} print(yaml.dump(aproject,))Copy the code

Dump must accept an open text or binary file as the second argument, and yaml. Dump writes the resulting YAMl document to the file

import yaml

aproject = {'name': 'jb',
            'race': 'jb',
            'traits': ['ONE_HAND', 'ONE_EYE']
            }
f = open(r'C:\Users\jb\gitprojects\jbtest\jb.yaml','w')
print(yaml.dump(aproject,f))
Copy the code

This will drop the desired content into the file ~

Dump_all, output multiple segments to the file to be given. The above example is one segment. If there are multiple segments, how do I land the file? At this point, you can use dump_all;

import yaml

obj1 = {"name": "jb", "age": 2}
obj2 = ["jb2", 3]

f = open(r'C:\Users\jb\gitprojects\jbtest\jb.yaml','w')
print(yaml.dump([obj1,obj2],f))
Copy the code

Output results:

Yaml, XML, JSON

There are only a few basic uses of YAML, and I don’t want to go any further.

Yaml is better than XML or json. XML is better than XML. Json is better than XML

<site> <site> <name>sina</name> <url>http://www.361way.com</url> </site> <site> <name> Google </name> <url>http://www.91it.org</url> </site> # use yaml to mark two sites -- site: name: sina url: http://www.361way.com -- site: Name: sina, url: http://www.361way.com} -- site: {name: sina, url: http://www.361way.com} -- site: {name: google, url: http://www.91it.org}Copy the code

Yaml feels much more intuitive from the perspective of viewing information

Yaml is very similar to JSON. Yaml is not as visible as XML, and Python provides methods to convert between the two.

Yaml to json

import yaml,json
yml = """
---
  foo: bar
"""
data = yaml.load(yml)
json = json.dumps(data)
print(json)
Copy the code

Output results:

{"foo": "bar"}
Copy the code

Turn json yaml:

import json,yaml
str = '{ "foo": "bar" }'
data = json.loads(str)
yml = yaml.safe_dump(data)
print(yml)
Copy the code

Output results:

{foo: bar}
Copy the code

Json is not that different from YAML

summary

Yaml is used to load, load_all, dump, duml_all, and XML

Thank you.