2022.06.19
本文按照YAML官方文档1.2.2版本翻译总结而成
This section provides a quick glimpse into the expressive power of YAML. It is not expected that the first-time reader grok all of the examples. Rather, these selections are used as motivation for the remainder of the specification.
本节简要介绍YAML的表达能力。第一次阅读的读者不可能熟读所有的例子。相反,这些选择被用作规范其余部分的动机。
YAML’s block collections use indentation for scope and begin each entry on its own line. Block sequences indicate each entry with a dash and space (“-
”). Mappings use a colon and space (“:
”) to mark each key/value pair. Comments begin with an octothorpe (also called a “hash”, “sharp”, “pound” or “number sign” - “#
”).
Example 2.1 Sequence of Scalars (ball players)
Mark McGwire
Sammy Sosa
Ken Griffey
Example 2.2 Mapping Scalars to Scalars (player statistics)
hr 65 # Home runs
avg 0.278 # Batting average
rbi 147 # Runs Batted In
Example 2.3 Mapping Scalars to Sequences (ball clubs in each league)
american
Boston Red Sox
Detroit Tigers
New York Yankees
national
New York Mets
Chicago Cubs
Atlanta Braves
Example 2.4 Sequence of Mappings (players’ statistics)
-
name Mark McGwire
hr65
avg0.278
-
name Sammy Sosa
hr63
avg0.288
YAML also has flow styles, using explicit indicators rather than indentation to denote scope. The flow sequence is written as a comma separated list within square brackets. In a similar manner, the flow mapping uses curly braces.
Example 2.5 Sequence of Sequences
name hr avg
Mark McGwire 65 0.278
Sammy Sosa 63 0.288
Example 2.6 Mapping of Mappings
Mark McGwire hr65 avg0.278
Sammy Sosa
hr63
avg0.288
YAML uses three dashes (“---
”) to separate directives from document content. This also serves to signal the start of a document if no directives are present. Three dots ( “...
”) indicate the end of a document without starting a new one, for use in communication channels.
Example 2.7 Two Documents in a Stream (each with a leading comment)
# Ranking of 1998 home runs
---
Mark McGwire
Sammy Sosa
Ken Griffey
# Team ranking
---
Chicago Cubs
St Louis Cardinals
Example 2.8 Play by Play Feed from a Game
---
time 20 0320
player Sammy Sosa
action strike (miss)
...
---
time 20 0347
player Sammy Sosa
action grand slam
...
Repeated nodes (objects) are first identified by an anchor (marked with the ampersand - “&
”) and are then aliased (referenced with an asterisk - “*
”) thereafter.
重复的节点(对象)首先由锚标识(用&号标记),然后别名(用星号引用- " ' * ' ")。
Example 2.9 Single Document with Two Comments
---
hr# 1998 hr ranking
Mark McGwire
Sammy Sosa
# 1998 rbi ranking
rbi
Sammy Sosa
Ken Griffey
Example 2.10 Node for “Sammy Sosa
” appears twice in this document
Sammy Sosa
的节点在本文档中出现了两次
x
---
hr
Mark McGwire
# Following node labeled SS
&SS Sammy Sosa
rbi
# Subsequent occurrence *SS
Ken Griffey
A question mark and space (“?
”) indicate a complex mapping key. Within a block collection, key/value pairs can start immediately following the dash, colon or question mark.
一个问号和一个空格(" ' ?' ")表示复杂的映射 key。在块集合中,键/值对可以紧跟着破折号,冒号或问号。
Example 2.11 Mapping between Sequences
? - Detroit Tigers
Chicago cubs
: - 2001-07-23
? New York Yankees
Atlanta Braves
: 2001-07-02 2001-08-12
2001-08-14
# "? "问号+空格表示复杂的键, 再如RGB与颜色对应
? [blue, red, green] Color
# 等价于下面
? - blue
red
green
: Color
Example 2.12 Compact Nested Mapping
---
# Products purchased
item Super Hoop
quantity1
item Basketball
quantity4
item Big Shoes
quantity1
Scalar content can be written in block notation, using a literal style (indicated by “|
”) where all line breaks are significant. Alternatively, they can be written with the folded style (denoted by “>
”) where each line break is folded to a space unless it ends an empty or a more-indented line.
|
可以保留多行字符串的换行符>
可以将多行字符串的换行符转换为一个空格Example 2.13 In literals, newlines are preserved
在字面值中,保留换行符
# ASCII Art
--- |
\//||\/||
// || ||__
Example 2.14 In the folded scalars, newlines become spaces
在折叠的标量中,换行成为空格
--- >
Mark McGwire's
year was crippled
by a knee injury.
Example 2.15 Folded newlines are preserved for “more indented” and blank lines
为“更缩进”和空白行保留折叠换行
--- >
Sammy Sosa completed another
fine season with great stats.
63 Home Runs
0.288 Batting Average
What a year!
下面是python-IDE中的案例
Python 3.7.6 (default, Jan 8 2020, 13:42:34)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import yaml
>>> a = '''>
... Sammy Sosa completed another
... fine season with great stats.
...
... 63 Home Runs
... 0.288 Batting Average
...
... What a year!'''
>>> print(yaml.load(a))
Sammy Sosa completed another fine season with great stats.
63 Home Runs
0.288 Batting Average
What a year!
>>>
Example 2.16 Indentation determines scope
name Mark McGwire
accomplishment
Mark set a major league
home run record in 1998.
stats
65 Home Runs
0.278 Batting Average
YAML’s flow scalars include the plain style (most examples thus far) and two quoted styles. The double-quoted style provides escape sequences. The single-quoted style is useful when escaping is not needed. All flow scalars can span multiple lines; line breaks are always folded.
YAML的流标量包括普通样式(到目前为止的大多数示例)和两个引用的样式。双引号样式提供转义序列。当不需要转义时,单引号样式很有用。所有流量标量可以跨越多行;换行符总是折叠。
Example 2.17 Quoted Scalars
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'|\-*-/|'
Example 2.18 Multi-line Flow Scalars
plain
This unquoted scalar
spans many lines.
quoted"So does this
quoted scalar.\n"
In YAML, untagged nodes are given a type depending on the application. The examples in this specification generally use the seq
, map
and str
types from the fail safe schema. A few examples also use the int
, float
and null
types from the JSON schema.
在YAML中,无标记节点根据应用场景给出了一种类型。本规范中的示例通常使用fail safe schema中的seq
、map
和str
类型。一些例子也使用了JSON模式中的int
, float
和null
类型。
Example 2.19 Integers
canonical12345
decimal +12345
octal 0o14
hexadecimal 0xC
Example 2.20 Floating Point
canonical 1.23015e+3
exponential 12.3015e+02
fixed1230.15
negative infinity -.inf
not a number .nan
Example 2.21 Miscellaneous
null
booleans true false
string'012345'
Example 2.22 Timestamps
canonical 2001-12-15T02 59 43.1Z
iso8601 2001-12-14t21 59 43.10-0500
spaced 2001-12-14 21 59 43.10 -5
date 2002-12-14
Explicit typing is denoted with a tag using the exclamation point (“!
”) symbol. Global tags are URIs and may be specified in a tag shorthand notation using a handle. Application-specific local tags may also be used.
显式输入用标记表示,并使用感叹号("!
")符号。Global tags是URIs,可以使用handle在tag简写表示法中指定。Application-specific local tags也可以使用。
Example 2.23 Various Explicit Tags
---
not-date !!str 2002-04-28
picture !!binary |
R0lGODlhDAAMAIQAAP//9/X
17unp5WZmZgAAAOfn515eXv
Pz7Y6OjuDg4J+fn5OTk6enp
56enmleECcgggoBADs=
application specific tag !something |
The semantics of the tag
above may be different for
different documents.
Example 2.24 Global Tags
%TAG ! tag:clarkevans.com,2002
--- !shape
# Use the ! handle for presenting
# tag:clarkevans.com,2002:circle
!circle
center&ORIGIN x73 y129
radius7
!line
start*ORIGIN
finish x89 y102
!label
start*ORIGIN
color 0xFFEEBB
text Pretty vector drawing.
Example 2.25 Unordered Sets
# Sets are represented as a
# Mapping where each key is
# associated with a null value
--- !!set
? Mark McGwire
? Sammy Sosa
? Ken Griffey
Example 2.26 Ordered Mappings
# Ordered maps are represented as
# A sequence of mappings, with
# each mapping having one key
--- !!omap
Mark McGwire65
Sammy Sosa63
Ken Griffey58
Below are two full-length examples of YAML. The first is a sample invoice; the second is a sample log file.
下面是两个完整的YAML示例。第一个是发票样本;第二个是示例日志文件。
Example 2.27 Invoice
--- !<tag:clarkevans.com,2002:invoice>
invoice34843
date 2001-01-23
bill-to&id001
given Chris
family Dumars
address
lines
458 Walkman Dr.
Suite #292
city Royal Oak
state MI
postal 48046
ship-to*id001
product
sku BL394D
quantity 4
description Basketball
price 450.00
sku BL4438H
quantity 1
description Super Hoop
price 2392.00
tax 251.42
total4443.52
comments
Late afternoon is best.
Backup contact is Nancy
Billsmer @ 338-4338.
Example 2.28 Log File
---
Time 2001-11-23 15 01 42 -5
User ed
Warning
This is an error message
for the log file
---
Time 2001-11-23 15 02 31 -5
User ed
Warning
A slightly different error
message.
---
Date 2001-11-23 15 03 17 -5
User ed
Fatal
Unknown variable "bar"
Stack
file TopClass.py
line23
code
x = MoreObject("345\n")
file MoreClass.py
line58
code -
foo = bar