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 McGwireSammy SosaKen GriffeyExample 2.2 Mapping Scalars to Scalars (player statistics)
hr65 # Home runsavg0.278 # Batting averagerbi147 # Runs Batted InExample 2.3 Mapping Scalars to Sequences (ball clubs in each league)
americanBoston Red SoxDetroit TigersNew York YankeesnationalNew York MetsChicago CubsAtlanta BravesExample 2.4 Sequence of Mappings (players’ statistics)
- nameMark McGwire hr65 avg0.278- nameSammy Sosa hr63 avg0.288YAML 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.278Sammy Sosa 63 0.288Example 2.6 Mapping of Mappings
Mark McGwirehr65 avg0.278Sammy 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 McGwireSammy SosaKen Griffey
# Team ranking---Chicago CubsSt Louis CardinalsExample 2.8 Play by Play Feed from a Game
---time200320playerSammy Sosaactionstrike (miss)...---time200347playerSammy Sosaactiongrand 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 rankingMark McGwireSammy Sosa# 1998 rbi rankingrbiSammy SosaKen GriffeyExample 2.10 Node for “Sammy Sosa” appears twice in this document
Sammy Sosa的节点在本文档中出现了两次
x
---hrMark McGwire# Following node labeled SS&SS Sammy Sosarbi*SS # Subsequent occurrenceKen GriffeyA 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 TigersChicago cubs: - 2001-07-23
? New York Yankees Atlanta Braves : 2001-07-02 2001-08-12 2001-08-14 # "? "问号+空格表示复杂的键, 再如RGB与颜色对应? [blue, red, green]Color# 等价于下面? - blueredgreen: ColorExample 2.12 Compact Nested Mapping
---# Products purchaseditem Super Hoop quantity1item Basketball quantity4item Big Shoes quantity1Scalar 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 darwinType "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
nameMark McGwireaccomplishment Mark set a major league home run record in 1998.stats 65 Home Runs 0.278 Batting AverageYAML’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
canonical12345decimal+12345octal0o14hexadecimal0xCExample 2.20 Floating Point
canonical1.23015e+3exponential12.3015e+02fixed1230.15negative infinity-.infnot a number.nanExample 2.21 Miscellaneous
nullbooleans true false string'012345'Example 2.22 Timestamps
canonical2001-12-15T025943.1Ziso86012001-12-14t215943.10-0500spaced2001-12-14 215943.10 -5date2002-12-14Explicit 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 color0xFFEEBB textPretty 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 GriffeyExample 2.26 Ordered Mappings
# Ordered maps are represented as# A sequence of mappings, with# each mapping having one key--- !!omapMark McGwire65Sammy Sosa63Ken Griffey58Below 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>invoice34843date 2001-01-23bill-to&id001 given Chris family Dumars address lines 458 Walkman Dr. Suite #292 city Royal Oak state MI postal 48046ship-to*id001productsku BL394D quantity 4 description Basketball price 450.00sku BL4438H quantity 1 description Super Hoop price 2392.00tax 251.42total4443.52comments Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.Example 2.28 Log File
---Time2001-11-23 150142 -5UseredWarning This is an error message for the log file---Time2001-11-23 150231 -5UseredWarning A slightly different error message.---Date2001-11-23 150317 -5UseredFatal Unknown variable "bar"StackfileTopClass.py line23 code x = MoreObject("345\n")fileMoreClass.py line58 code- foo = bar