1. 程式人生 > 實用技巧 >YAML - Study Notes

YAML - Study Notes

A singleline breakisfoldedinto a singlespace, whileempty linesare interpreted asline breakcharacters.

YAML can therefore be viewed as a natural superset of JSON, offering improved human readability and a more complete information model. This is also the case in practice; every JSON file is also a valid YAML file. This makes it easy to migrate from JSON to YAML if/when the additional features are required.

JSON'sRFC4627requires thatmappingskeysmerely “SHOULD” beunique, while YAML insists they “MUST” be. Technically, YAML therefore complies with the JSON spec, choosing to treat duplicates as an error. In practice, since JSON is silent on the semantics of such duplicates, the only portable JSON files are those with unique keys, which are therefore valid YAML files.

Block Style:

YAML’sblock collectionsuseindentationfor scope and begin each entry on its own line.Block sequencesindicate each entry with a dash and space(-).Mappingsuse a colon and space(:) to mark eachkey:value pair.Commentsbegin with an octothorpe (also called a “hash”, “sharp”, “pound”, or “number sign” -

#).

Example2.1. Sequence of Scalars
(ball players)

- Mark McGwire
- Sammy Sosa - Ken Griffey

Example2.2. Mapping Scalars to Scalars
(player statistics)

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

Example2.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

Example2.4. Sequence of Mappings
(players’ statistics)

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

Flow Style:

YAML also hasflow styles, using explicitindicatorsrather thanindentationto denote scope. Theflow sequenceis written as acommaseparated list withinsquarebrackets. In a similar manner, theflow mappingusescurlybraces.

Example2.5.Sequence of Sequences

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

Example2.6.Mapping of Mappings

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

Copied from:https://yaml.org/spec/1.2/spec.html