YAML Basics
YAML is a human-readable data serialization
language that is often used for writing configuration files.
Scalars and Basic Data Types
In YAML, scalars represent simple data types like strings, numbers, booleans, and null. Let's start with these basic data types.
Strings:
Strings are sequences of characters and don't require quotes unless they contain special characters or spaces.
Examples:
name: John Doe
email: john@example.commessage: "Hello, World!"
Numbers:
Numeric values can be integers or floating-point numbers.
Examples:
age: 30
pi: 3.14159
Booleans:
Booleans represent true or false values.
Examples:
is_student: true
has_car: false
Null:
The keyword null
represents the absence of a value.
Example:
description: null
Lists and Sequences
Lists in YAML are used to represent sequences of items. Each item is preceded by a hyphen (-
) followed by a space.
Lists:
Examples:
fruits:
- apple- banana- orange
Nested Lists:
Lists can be nested to create more complex structures.
Example:
people:
- name: John Doeage: 30- name: Jane Smithage: 25
Dictionaries and Mappings
Dictionaries (also called maps or objects) in YAML use key-value pairs to represent data. Each key-value pair is denoted by a colon (:
).
Dictionaries:
Example:
person:
name: John Doeage: 30
Nested Dictionaries:
Dictionaries can be nested to create hierarchical structures.
Example:
user:
profile:name: John Doeage: 30
Multi-line Strings and Special Characters
Multi-line strings can be represented using the |
character for block literals or >
for folded blocks.
Multi-line Strings (Block Literal):
Example:
message: |
This is a multi-linestring using a block literal.It preserves line breaks.
Multi-line Strings (Folded Block):
Example:
description: >
This is a folded blockstring. It removes line breaksbut keeps the content.
Anchors and Aliases
Anchors (&
) and aliases (*
) allow you to reuse data in multiple places within the YAML file.
Example:
defaults: &default_values
timeout: 30retries: 3server1: <<: *default_values host: example.com server2: <<: *default_valueshost: test.com
These are the basics of YAML. With this foundation, you can start writing YAML files and understanding more complex YAML structures used in different applications and frameworks.
Comments
Post a Comment