Skip to content

YAML – 流式样式

YAML 的流式风格提供了一种紧凑的、通常是单行的方式来表示集合(序列和映射)和标量。它们在语法上类似于 JSON,特别适用于简单数据结构或将数据嵌入到较大的块式风格结构中。本章探讨常见的流式风格结构。

流式风格的特点是使用显式分隔符:[] 用于序列,{} 用于映射。

流式序列用方括号 [] 括起来,项目之间用逗号(可选加上空格)分隔。示例:

colors: [red, green, blue]
empty_list: []
mixed_types: [1, "apple", true, {type: "fruit"}]

colors 的 JSON 等效形式为:{"colors": ["red", "green", "blue"]}

流式映射用花括号 {} 括起来,键值对之间用逗号分隔。键和值之间用冒号和空格分隔。示例:

user: {name: "Alice", age: 28, city: "London"}
empty_object: {}
config: {enabled: true, port: 8080}

user 的 JSON 等效形式为:{"user": {"name": "Alice", "age": 28, "city": "London"}}

虽然标量本身不像集合那样有明显的“流式”分隔符,但它们是流式集合中的内容。流式标量可以是普通(不加引号)、单引号或双引号。

# 流式序列中的标量
items: [plain_scalar, 'single quoted', "double quoted with \"escapes\""]
# 流式映射中的标量
details: {id: 123, notes: 'A simple note.', message: "Status: OK"}

空值或 null 可以在流式风格中用 null 或 ~ 表示,或者用空标量值表示(例如,字符串)。

data: { key1: null, key2: ~, key3: '', key4: }

上述内容的 JSON 输出:

{
"data": {
"key1": null,
"key2": null,
"key3": "",
"key4": null
}
}

锚点 (&) 和别名 (*) 与流式风格无缝配合,允许数据重用。

# YAML 1.2
default_config: &defaults { timeout: 5000, retries: 3 }
service1_config: { <<: *defaults, port: 8081 } # 与默认值合并
service2_config: { <<: *defaults, port: 8082, timeout: 10000 } # 覆盖 timeout
user_list:
- &user1 { name: "Bob" }
- { name: "Charlie" }
admin_users: [*user1]

JSON 输出(解析锚点/别名和合并后):

{
"default_config": { "timeout": 5000, "retries": 3 },
"service1_config": { "timeout": 5000, "retries": 3, "port": 8081 },
"service2_config": { "timeout": 10000, "retries": 3, "port": 8082 },
"user_list": [
{ "name": "Bob" },
{ "name": "Charlie" }
],
"admin_users": [
{ "name": "Bob" }
]
}

流式集合可以相互嵌套,或嵌套在块式集合中。

matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
complex_object:
id: "obj123"
properties: {color: "blue", size: "large"}
tags: ["tagA", "tagB"]
# Flow mapping with a flow sequence value
coordinates: { x_values: [10, 20, 30], y_values: [15, 25, 35] }

matrix 的 JSON 输出:

{
"matrix": [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
}
  • 对于简单的、紧凑的数据结构,当行内表示清晰时。
  • 当数据与 JSON 对象或数组非常相似时。
  • 将小型集合嵌入到块式结构中(例如,博客文章的标签列表)。
  • 当生成需要能被更简单的 JSON 工具轻松解析的 YAML 时(尽管直接输出 JSON 通常更好)。

注意:对于复杂数据,过度使用深层嵌套的流式风格会显著降低可读性,不如对应的块式风格。通常最好保持平衡,选择最适合数据复杂性和清晰度需求的风格。