YAML: Syntax, Use Cases, and Practical Parsing
What's a Yaml?
The questions in this article can also be addressedJSON and JSONL Speed、SQL Foundation: Query, Aggregation, JOIN and Window FunctionsHow the concept of a relatively close read together is developed in different contexts.
YAML's full name was first understood as Yet Another Markup Language, later interpreted as YaML Ain't Markup Language. The name itself is interesting: it starts as a sign language, and then stresses that it is not a mark language, but a data sequence format. In short, the YamL is used to express the data structure, the most common suffix is .yaml or .yml。
If JSON's goal is to stabilize the machine and exchange data, YAML is more comfortable with configuration. It does not require a double quote for each key, nor does it need to write commas at the end of each, a hierarchy by indentation, and an annotated note can be written directly in the document. These advantages are clear for the configuration document: one can see the hierarchy at a glance, and changing one parameter is not easily interrupted by a pile of brackets and commas.
So we often see YAML in the configuration scene: the front matter of blog articles, GitHub Actions workflow, Docker Company, Kubernets Manifest, Ansible Playbook, model training configuration, service deployment configuration, all of which are preferred. It's not a core value "more advanced than JSON" but "more suitable for handwritten and maintenance."
YAML and JSON are close. Many Yaml files express data structures that are eventually deciphered to the normal objects of the program Map, List, String, Nuber, Boolean, Null. So, YAML is not a mysterious format, and it's still going back to the data structure that the program can handle.
Basic YamL
The most basic structure for YAML is the key pair. The colon is key on the left, and the colon is value on the right.
name: Jake
age: 25
city: Wuhan
is_student: true
After this, it becomes, in general, the object:
{
"name": "Jake",
"age": 25,
"city": "Wuhan",
"is_student": true
}
The level of YAML is indented. Usually use two spaces, not tab. This is a very important habit, because the YamL is sensitive to indentation, and the data structure is wrong.
user:
name: Jake
age: 25
profile:
email: jake@example.com
location: Wuhan
In this example,name and age belong user,email and location belong profileI'm sorry. YAML does not need {} To wrap objects, to indent the structure to naturally expand.
List with Short Line - - Show. Short-wire lines themselves follow indentation rules.
hobbies:
- Swimming
- Basketball
- Reading
Object arrays are also common. A group of blog posts can be written as follows:
posts:
- id: 1
title: 第一篇文章
tags:
- Python
- Data
published: true
- id: 2
title: 第二篇文章
tags:
- YAML
- Config
published: false
It's like the object array in JSON, but YAML saved brackets, commas and quotes. The omission of those symbols made the document easier to read, but the price was that indentation had to be more serious.
YamL supports the comment. Comment from # Start, end of line.
# 站点基本信息
site:
title: Hyacehila
language: zh-CN # 默认语言
The comment is one of the important reasons why YaML is well suited to the profile. JSON cannot write an comment in standard formats, so many items are added to JSONC or are written in the document. YAML can place the explanation directly next to the configuration.
The string in YAML is usually not accompanied by quotation marks.
title: YAML 格式与使用速成
path: /blog/2026/07/06/yaml-format-usage-learning-notes/
But when the string contains elements that are easily misunderstood, it is advisable to add a reference sign. Examples include colons, wells, special booleans, back and forth spaces, version numbers, times, dates, etc.
title: "YAML: Syntax, Use Cases, and Practical Parsing"
version: "1.0"
answer: "no"
created_at: "2026-07-06 20:04:07"
YAML automatically resolves some values into numbers, booleans or empty values.
count: 10
ratio: 0.8
enabled: true
disabled: false
empty_value: null
also_empty:
Here. count It's the integer number.ratio It's floating point number.enabled It's a boolean value.empty_value and also_empty Could be parsed to empty values. This automatic type of extrapolation is convenient, but it is also one of the most common pits in the YamL, which will be discussed separately later.
Multiline String
YAML handles long text much more comfortable than JSON. The two most common ways are: | and >。
| indicates that the line is reserved. The text is basically retained as it is transposed.
description: |
这是第一行。
这是第二行。
这是第三行。
This is appropriate to save scripts, certificates, hint templates, email body, Markdown clips, etc., which require a line break.
script: |
npm install
npm run build
npm run check:i18n
> is a folding line. Multiline text is folded into a more nuanced form.
summary: >
YAML 很适合写配置文件,
因为它比 JSON 更方便人类阅读和编辑,
但它也更依赖缩进和解析规则。
If you want to keep a long description in the profile file from being too long, you can't be sure that the profile is too long.> It'll be more natural. If you really need to keep the boundaries of each line, such as shell scripts, prompt templates, Nginx configurations, you should use |。
The difference is important in engineering. Many times the profile does not contain simple parameters, but rather a command, a template, a description text. Wrong. | and >And the strings that the program sees will be different from what you think.
YAML common use of scenes
The first very daily scene is the front matter of blog articles. Many static blog systems will start with a YamL metadata section in the Markdown file, informing the system about the title, date, classification, label, summary of the article.
---
title: "YAML 格式与使用速成"
date: 2026-07-06 20:04:07 +0800
categories: ["Programming", "Computer Science Fundamentals"]
tags: ["Learning Notes", "YAML"]
hidden: true
---
The text here is still Markdown, but this opening part. --- The area will be analyzed as YAML first. The fields are read in the theme, archive, tab page, front page card.
The second common scene is GitHub Actions. CI/CD configuration is particularly appropriate for YAML because it has a clear hierarchy: what triggers an event, which system runs, which job, which steps each job has.
name: buildon: push: branches: - master
jobs: site: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Install dependencies run: npm install - name: Build run: npm run build
This configuration, if written in JSON, will have a large number of brackets and string quotation marks; it will be written in YAML, more like a readable implementation list.
The third scene is Docker Company. It uses YAML to describe the relationship between multiple services.
services: web: image: nginx:latest ports: - "8080:80" volumes: - ./site:/usr/share/nginx/html:ro
redis: image: redis:7 restart: unless-stopped
Here, the YAML expression is just enough: the service name is key, and mirrors, ports, rolls, restarts are fields. It's very close to "What components are the systems?"
The fourth scene is Kubernetes. The Kubernetes resource audience is usually YAML prime.
apiVersion: apps/v1
kind: Deployment
metadata:
name: blog
spec:
replicas: 2
selector:
matchLabels:
app: blog
template:
metadata:
labels:
app: blog
spec:
containers:
- name: blog
image: hyacehila/blog:latest
ports:
- containerPort: 4000
The Kubernetes Yaml also explains another aspect of YAML: When the configuration is too complex, it becomes long and easily duplicates the paste. YAML is not a silver bullet in a complex system, it just makes the configuration object more easily edited directly.
The fifth scenario is to apply its own configuration file.
server: host: 0.0.0.0 port: 8080database: url: postgresql://localhost:5432/app pool_size: 10 timeout_seconds: 30
features: enable_cache: true enable_experiment: false
This configuration is usually eventually read into a dictionary or object. The application should not simply treat YAML as a string, but should read it in the solver, then bind it with type check, schema or default value logic.
How to deal with YAML
The most common YamL library in Python is Pyyaml. Use YAML first when reading safe_load, do not use unsafe loads.
import yamlraw = """ server: host: 0.0.0.0 port: 8080 features: enable_cache: true """
config = yaml.safe_load(raw)
print(config["server"]["host"]) print(config["server"]["port"]) print(config["features"]["enable_cache"])
yaml.safe_load() The YAML string is to be resolved to Python objects. The general correspondence is as follows:
- YAML mapping -> Python
dict - YAML sequence -> Python
list - YAML string -> Python
str - YAML integer -> Python
int - YAML float -> Python
float - YAML boolean -> Python
bool - YAML null -> Python
None
If it is read from a document, it is written directly.
import yamlfile_path = "config.yaml"
with open(file_path, "r", encoding="utf-8") as f: config = yaml.safe_load(f)
print(config)
Write Yaml to use safe_dumpI'm sorry. If you have Chinese, you usually have to set it up. allow_unicode=TrueOtherwise, Chinese might be replaced.
import yamlconfig = { "site": { "title": "YAML 格式与使用速成", "language": "zh-CN", }, "features": { "search": True, "comments": False, }, }
with open("config.yaml", "w", encoding="utf-8") as f: yaml.safe_dump( config, f, allow_unicode=True, sort_keys=False, )
sort_keys=False It's common. The configuration file is often readable, the field order is meaningful and does not necessarily want the library to be automatically alphabetical.
JavaScript or Node.js, available js-yaml This kind of library.
const yaml = require("js-yaml");const raw =
server: host: 0.0.0.0 port: 8080 features: enable_cache: true;const config = yaml.load(raw);
console.log(config.server.host); console.log(config.server.port); console.log(config.features.enable_cache);
When read from a file, you can cooperate fs.readFileSync。
const fs = require("fs"); const yaml = require("js-yaml");const raw = fs.readFileSync("config.yaml", "utf8"); const config = yaml.load(raw);
console.log(config);
Write YAML dump。
const fs = require("fs"); const yaml = require("js-yaml");const config = { site: { title: "YAML 格式与使用速成", language: "zh-CN", }, features: { search: true, comments: false, }, };
const output = yaml.dump(config, { lineWidth: 100, noRefs: true, });
fs.writeFileSync("config.yaml", output, "utf8");
When you write a profile, reading and writing is not usually the hardest. And even harder: how to figure out how to prove it is the structure you want. In the real project, it is advisable to add a schema or a visible validation to the YaML configuration. Like what? port It must be numbers,host Must be a string,features Only allowed switches can appear below. Do not default on the fact that the YamL file must be a valid configuration because it looks like a configuration.
Yaml's pit
YAML's first pit is indented. JSON expresses the hierarchy in brackets, and the error in brackets is obvious; YAML expresses the hierarchy in indentation, and the error in a space is sometimes difficult to find in the naked eye.
user:
name: Jake
profile:
email: jake@example.com
city: Wuhan
If you don't, it's written like this:
user:
name: Jake
profile:
email: jake@example.com
city: Wuhan
city I'm not a part of it anymore. profile, instead of the peace profile Same grade. It may still be legal, but the semantics have changed. This is the most problematic because the solver will not always report the error, but will only faithfully decipher the other structure.
The second pit is tab. YAML Indents Do Not Use Tab, Unique Space. Team best configure editor, auto-convert tab to spaces and display invisible characters. It looks like a little habit, and it's gonna take a lot of weird mistakes.
The third pit is of a hidden type. YAML automatically guesses the type, which is convenient in simple configuration, dangerous in border scenes. For example, the following values, preferably with quotation marks:
version: "1.0"
answer: "no"
switch: "on"
date: "2026-07-06"
time: "20:04:07"
hex_like: "0x10"
Different YaML versions, different solvers, different library options may not be interpreted in the same way as certain values. To reduce uncertainty, you can add a quote directly to any you want it to keep the value of the string. In particular, ID, version number, date, count, command parameters should not be given to the decryptator to guess.
The fourth pit is the colon and the well. Yaml : and # It's a grammar. If they appear in a string, it is advisable to add quotation marks.
title: "YAML: Syntax, Use Cases, and Practical Parsing"
command: "echo hello # this is not a yaml comment"
url: "https://example.com/a:b"
The fifth pit is a repeat key. This configuration below looks like it's only written twice. port:
server:
port: 8080
port: 9000
But many of the solvers will simply keep the latter value, the previous one being overwritten. More troublesomely, this may not be a mistake. For the configuration file, repetition of key often means that there is a problem with copying paste or merging configurations. Better use the Linter or schema tools to stop early.
The sixth pit is anchor and aliases. YamL support & Define anchor, use * It's still working. << Merges fields.
defaults: &defaults image: node:22 restart: unless-stopped environment: NODE_ENV: production
services: api: <<: *defaults command: npm run start:api worker: <<: *defaults command: npm run start:worker
This capacity is useful and reduces duplication. But it also allows the document to move slowly from " configuration " to " configuration with a logic of expansion " . If a YamL needs readers to leap, merge, and cover in their minds, the cost of maintenance increases. The anchor is suitable for a small number of reuses and does not fit the configuration into a puzzle.
The seventh pit is multi-document. YAML, a file can be used. --- Splits multiple documents.
---
kind: ConfigMap
metadata:
name: app-config
---
kind: Secret
metadata:
name: app-secret
It's common in Kubernetes, but when you're deciphered, it's normal. safe_load Could be suitable for single documents only. If there are multiple documents in the file, it's usually used in Python safe_load_all。
import yamlwith open("resources.yaml", "r", encoding="utf-8") as f: documents = list(yaml.safe_load_all(f))
for doc in documents: print(doc["kind"])
The eighth pit is safe. Do not use unsafe resolution for untrustworthy sources of Yaml. Some of the YAML advanced abilities and object construction capabilities may allow the process to go beyond “reading data”. For the ordinary profile,safe_load Such a safe resolution is sufficient. The more YAML is uploaded by users, external services, network input, the more conservative it should be.
When won't you need it, Yaml?
YAML is a good human-written configuration, but does not mean that all structured data should be used.
If data is transmitted between services, give priority to JSON. JSON is more stringent, solvers are more uniform, more ecologically stable, and more suitable for API requests and responses. HTTP API returns to YamL is not an option, but in most of the scenes, JSON will make the caller easier.
For large-scale logs, training data, reptile results, model input output records, priority is given to JSONL. JSONL is a complete JSON object in each line, which is natural for addition, streaming and segment processing. YAML can express object arrays, but if the data is large, an entire YAML file will become less suitable for current processing.
If it's a very complex configuration that needs to be robust, be careful with YamL. Many of the engineering accidents were not because YAML was unable to express them, but because it was too expressive, and the final project used a configuration format as half a DSL. Once a large number of anchors, templates, conditions, inheritance, rules of coverage have begun to emerge in the configuration, it is difficult for one to judge what the configuration ultimately takes effect.
There are several more stable approaches at this time: binding the configuration with tools such as JSON Schema, OpenAPI, Pydantic, Zod; moving complex logic into the normal code; or providing the generator and the checker for the configuration, rather than allowing the person to write all the details by hand.
So the YamL border can be understood as follows:It is appropriate to express static, hierarchically clear, primarily manned configurations; it is not suitable to carry high frequency transmissions, large-scale current data and overly complex business logic.
Summary
The advantages of YAML are straightforward: less brackets, less quotation marks, more commentable, clear hierarchy, and appropriate configuration. It allows for the natural expression of objects, lists, strings, numbers, booleans and empty values in a text file, and for the comfortable writing of multiple lines of text.
But the dangers of YAML are also due to these advantages. It relies too much on indentation, it is too confident in people's reading instincts, and it also makes automatic type extrapolations. A lot of Yaml documents look so clear, they don't really solve the tree in your head. Several habits are to be developed when writing YAML: to unify two spaces indents without tab; to add quotation marks if the string is uncertain; to complex configurations plus schema; to check repeat key with the loger; to use security resolution when reading external YAML.
YAML is more like a hand-held configuration note than JSON; YAML is less suitable for current data than JSON; and YAML should not have too much logic than code. Put it in the right place, it'll be very easy. It becomes a maintenance burden, slowly, as an inescapable configuration language.
I think the simplest way to judge is if this document is written primarily by people, read by programs, and is structured at a more complex level than a plain text, and not so complicated as to require code writing, then Yamal is a good choice. If this document is mainly machine-generated, machine-consuming, HF-exchange, strong schema, or fluent processing, then it should be carefully considered, JSON, JSONL, or a more explicit configuration system.
- Title: YAML: Syntax, Use Cases, and Practical Parsing
- Author: Hyacehila
- Created at : 2025-10-15 15:55:21
- Link: https://hyacehila.github.io//blog/2025/10/14/yaml-format-usage-learning-notes/
- License: This work is licensed under CC BY-NC-SA 4.0.