Basic Syntax for Defining a Key-Value Pair in YAML

YAML (YAML Ain't Markup Language) uses a simple and intuitive syntax for defining key-value pairs. A key-value pair is a fundamental concept in YAML, where a key is associated with a value. This structure allows for the representation of data in a clear and organized manner.

Key-Value Pair Structure

The basic syntax for defining a key-value pair in YAML consists of the following components:

  • Key: The name or identifier for the data. It is followed by a colon (:) and a space.
  • Value: The data associated with the key. This can be a string, number, boolean, list, or another nested structure.

Basic Example

Here is a simple example of a key-value pair in YAML:

        
name: John Doe
age: 30
is_student: false

In this example:

  • name is the key, and its value is John Doe.
  • age is the key, and its value is 30.
  • is_student is the key, and its value is false.

Nested Key-Value Pairs

YAML also allows for nested key-value pairs, enabling the representation of more complex data structures. To define nested key-value pairs, you simply indent the nested keys under their parent key.

        
person:
name: John Doe
age: 30
address:
street: 123 Main St
city: Anytown
state: CA

In this example:

  • person is the parent key, and it contains three nested key-value pairs: name, age, and address.
  • address itself contains three nested key-value pairs: street, city, and state.

Lists as Values

YAML also supports lists as values. You can define a list by using a dash (-) followed by a space before each item in the list.

        
hobbies:
- reading
- traveling
- swimming

In this example, hobbies is a key that has a list of values: reading, traveling, and swimming.

Conclusion

In summary, the basic syntax for defining a key-value pair in YAML is straightforward and intuitive. By using colons to separate keys from values and indentation to represent nested structures, YAML provides a clear and organized way to represent data. This simplicity and readability make YAML a popular choice for configuration files and data serialization.