YAML简单使用

608 阅读2分钟

YAML是一种数据序列化语言,通常用于编写配置文件。

本文仅仅摘抄YAML说明文档中的部分内容,方便使用YAML时查看。

集合(Collections)

纯量的序列:

- Mark McGwire
- Sammy Sosa
- Ken Griffey

纯量到纯量的映射:

hr:  65    # Home runs
avg: 0.278 # Batting average
rbi: 147   # Runs Batted In

(# 后面的是注释的内容)

纯量到序列的映射:

american:
- Boston Red Sox
- Detroit Tigers
- New York Yankees
national:
- New York Mets
- Chicago Cubs
- Atlanta Braves

映射的序列:

-
  name: Mark McGwire
  hr:   65
  avg:  0.278
-
  name: Sammy Sosa
  hr:   63
  avg:  0.288

序列的序列:

- [name        , hr, avg  ]
- [Mark McGwire, 65, 0.278]
- [Sammy Sosa  , 63, 0.288]

映射的映射:

Mark McGwire: {hr: 65, avg: 0.278}
Sammy Sosa: {
    hr: 63,
    avg: 0.288,
 }

结构体(Structures)

YAML使用---来分隔指令和文档内容。如果没有指令,---就表示文档的开头,可选的...表示文档的结束,但是不会打开新的文档,用于通信通道。

# Ranking of 1998 home runs
---
- Mark McGwire
- Sammy Sosa
- Ken Griffey

# Team ranking
---
- Chicago Cubs
- St Louis Cardinals

纯量 (Scalars)

字面量,--- 后面是|,换行会被保留:

# ASCII Art
--- |
  \//||\/||
  // ||  ||__

字面量,---后面是>换行会变成空格:

--- >
  Mark McGwire's
  year was crippled
  by a knee injury.

用引号包围的纯量:

unicode: "Sosa did fine.\u263A"
control: "\b1998\t1999\t2000\n"
hex esc: "\x0d\x0a is \r\n"

single: '"Howdy!" he cried.'
quoted: ' # Not a ''comment''.'
tie-fighter: '|\-*-/|'

标记 (Tags)

整数:

canonical: 12345
decimal: +12345
octal: 0o14
hexadecimal: 0xC

浮点数:

canonical: 1.23015e+3
exponential: 12.3015e+02
fixed: 1230.15
negative infinity: -.inf
not a number: .nan

其他:

null:
booleans: [ true, false ]
string: '012345'

时间戳:

canonical: 2001-12-15T02:59:43.1Z
iso8601: 2001-12-14t21:59:43.10-05:00
spaced: 2001-12-14 21:59:43.10 -5
date: 2002-12-14