YAML(YAML Ain't Markup Language)是一种简洁、可读性高的数据序列化格式。它常用于配置文件和数据交换。YAML 的语法非常灵活且易于理解。
以下是 YAML 的基本语法和结构:
1. 基本语法规则
- 大小写敏感。
- 使用缩进表示层级关系,通常使用两个空格(不能使用 Tab 键)。
- 键值对格式:
key: value。 - 注释 使用
#,后面的内容将被忽略。
2. 数据类型
YAML 支持多种常见的数据类型:
2.1 字符串(Strings)
字符串可以不使用引号,也可以使用单引号或双引号包裹。
yaml
name: John Doe # 不带引号的字符串
single_quote: 'John' # 单引号
double_quote: "Doe" # 双引号2.2 数字(Numbers)
YAML 支持整数和浮点数。
yaml
age: 30
height: 1.752.3 布尔值(Booleans)
布尔值为 true 或 false,也可以使用 yes/no。
yaml
is_student: true
is_employed: no2.4 空值(Null)
可以使用 null 或 ~ 表示空值。
yaml
middle_name: null
nickname: ~3. 复杂数据类型
3.1 列表(Lists)
使用 - 表示列表中的元素,每个元素占一行。
yaml
fruits:
- Apple
- Orange
- Banana或者可以写成单行形式:
yaml
fruits: [Apple, Orange, Banana]3.2 字典(Dictionaries / Mappings)
键值对用 : 分隔,可以嵌套字典。
yaml
person:
name: John Doe
age: 30
address:
street: 123 Main St
city: New York3.3 列表嵌套字典
列表中的每个元素都可以是一个字典。
yaml
people:
- name: John Doe
age: 30
- name: Jane Doe
age: 253.4 字典嵌套列表
字典的某个值可以是一个列表。
yaml
company:
name: Tech Corp
employees:
- John Doe
- Jane Smith
- Alice Brown4. 引用与别名
YAML 支持引用和别名来避免重复定义数据。
yaml
defaults: &defaults
adapter: postgres
host: localhost
development:
<<: *defaults
database: dev_db
production:
<<: *defaults
database: prod_db上面的 <<: *defaults 是一种引用,它表示 development 和 production 将继承 defaults 中定义的内容。
5. 多行字符串
使用 | 或 > 来表示多行字符串。
|保留换行符。>将换行符替换为空格。
yaml
description: |
This is a
multi-line string.
summary: >
This is a long
string that will be
folded into a single line.6. YAML 示例
yaml
# 一个简单的 YAML 文件
name: "My Project"
version: 1.0
license: MIT
# 列表
languages:
- JavaScript
- Python
- Java
# 嵌套结构
author:
name: John Doe
email: john.doe@example.com
# 布尔值和数字
is_active: true
contributors: 3
# 多行字符串
description: |
This project is designed to demonstrate YAML syntax.
It contains multiple examples of data types.
# 引用和别名
default_settings: &default_settings
host: localhost
port: 8080
development:
<<: *default_settings
mode: debug
production:
<<: *default_settings
mode: release小结
YAML 语法简单易读,尤其适合用来做配置文件。了解其缩进、列表、字典等规则可以让你更好地掌握它。在使用 YAML 时,记得保持一致的缩进,并遵循基本的语法规则。

