YAML基础
程序员文章站
2023-12-30 18:30:16
...
文章目录
YAML基础
YAML:用来表示数据序列化的一种语言。
基本格式要求
- YAML大小写敏感;
- 使用缩进代表层级关系;
- 缩进只能使用空格,不能使用TAB,不要求空格个数,只需要相同层级左对齐(一般2个或4个空格)。
三种格式:scalar、map 和 lsit
- scalar:数据最小的单位,不可分割
- map:使用
:
表示键值对 - list:使用
-
表示
例子1:Sequence of Scalars
常见的 scalars:
- hello World # 字符串, 不用加单引号或者双引号
- true # 布尔值: true,false
- 18 # 整数
- 12.3 # 浮点数
- ~ # null
- 2018-9-30t15:13:30 # 时间
- 2018-9-30 # 日期
# JSON的表示结果
[ 'hello World',
true,
18,
12.3,
null,
Sun Sep 30 2018 23:13:30 GMT+0800 (中国标准时间),
'2018-9-30'
]
ball players
- Mark McGwire
- Sammy Sosa
- Ken Griffey
# JSON的表示结果
[ 'Mark McGwire - Sammy Sosa - Ken Griffey' ]
例子2:Mapping Scalars to Scalars
player statistics
hr: 65 # Home runs
avg: 0.278 # Batting average
rbi: 147 # Runs Batted In
# JSON
{ hr: 65, avg: 0.278, rbi: 147 }
例子3:Mapping Scalars to Sequence
ball clubs in each league
american:
- Boston Red Sox
- Detroit Tigers
- New York Yankees
national:
- New York Mets
- Chicago Cubs
- Atlanta Braves
# JSON:
{
american: [ 'Boston Red Sox', 'Detroit Tigers', 'New York Yankees' ],
national: [ 'New York Mets', 'Chicago Cubs', 'Atlanta Braves' ]
}
例子4:Sequence of Mappings
players’s statistics
-
name: Mark McGwire
hr: 65
avg: 0.278
-
name: Sammy Sosa
hr: 63
avg: 0.288
# JSON
[
{ name: 'Mark McGwire', hr: 65, avg: 0.278 },
{ name: 'Sammy Sosa', hr: 63, avg: 0.288 }
]
例子5:Sequence of Sequences
- [name, hr, avg]
- [Mark McGwire, 65, 0.278]
- [Sammy Sosa, 63, 0.288]
# JSON
[
[ 'name', 'hr', 'avg' ],
[ 'Mark McGwire', 65, 0.278 ],
[ 'Sammy Sosa', 63, 0.288 ]
]
例子6:Mapping of Mappings
Mark McGwire: {hr: 65, avg: 0.278}
Sammy Sosa: {hr: 63, avg: 0.288}
# JSON
{
'Mark McGwire': { hr: 65, avg: 0.278 },
'Sammy Sosa': { hr: 63, avg: 0.288 }
}
例子7:& 与 *
- &:可以用来设置锚点;
- *:可以用来使用锚点。
hr: # 1998 hr ranking
- Mark McGwire
# Following node labeled SS
- &SS Sammy Sosa
rbi:
# 1998 rbi ranking
- *SS # Subsequent occurrence
- Ken Griffey
# JSON:
{
hr: [ 'Mark McGwire', 'Sammy Sosa' ],
rbi: [ 'Sammy Sosa', 'Ken Griffey' ]
}
等效于:
hr: # 1998 hr ranking
- Mark McGwire
# Following node labeled SS
- Sammy Sosa
rbi:
# 1998 rbi ranking
- Sammy Sosa
- Ken Griffey
例子8:符号 |
>``-``+
!!
-
|
>
: 多行字符串可以使用|
保留换行符,也可以使用>
折叠换行; -
-
+``:
-:表示删除字符串末尾的换行;
+`表示保留字符串末尾的换行; -
!!
:表示强制转换。
name: Mark McGwire
accomplishment: >-
Mark set a major league
home run record in 1998.
stats: |+
65 Home Runs
0.278 Batting Average
age: !!str 34
# JSON
{
name: 'Mark McGwire',
accomplishment: 'Mark set a major league home run record in 1998.', # 末尾换行符删除了
stats: '65 Home Runs\n0.278 Batting Average\n' # 末尾换行符保留了
age: '34'
}