YAML

YAML is a data serialisation language designed to be directly writable and readable by humans.

It’s a strict superset of JSON, with the addition of syntactically significant newlines and indentation, like Python. Unlike Python, however, YAML doesn’t allow literal tab characters for indentation.

Install pyyaml package:

pip install pyyaml

Example Python script:

import yaml

sample_yaml_as_dict = '''
first_dict_key: some value
second_dict_key: some other value
'''

sample_yaml_as_list = '''
- list item 1
- list item 2
'''

my_config_dict = yaml.load(sample_yaml_as_dict)
print(my_config_dict)

my_config_list = yaml.load(sample_yaml_as_list)
print(my_config_list)

Output:

python python_yaml.py
{'first_dict_key': 'some value', 'second_dict_key': 'some other value'}
['list item 1', 'list item 2']

Example YAML file:

# Comments in YAML look like this.

################
# SCALAR TYPES #
################

# Our root object (which continues for the entire document) will be a map,
# which is equivalent to a dictionary, hash or object in other languages.
key: value
another_key: Another value goes here.
a_number_value: 100
scientific_notation: 1e+12
# The number 1 will be interpreted as a number, not a boolean. if you want
# it to be interpreted as a boolean, use true
boolean: true
null_value: null
key with spaces: value
# Notice that strings don't need to be quoted. However, they can be.
however: 'A string, enclosed in quotes.'
'Keys can be quoted too.': "Useful if you want to put a ':' in your key."
single quotes: 'have ''one'' escape pattern'
double quotes: "have many: \", \0, \t, \u263A, \x0d\x0a == \r\n, and more."

# Multiple-line strings can be written either as a 'literal block' (using |),
# or a 'folded block' (using '>').
literal_block: |
    This entire block of text will be the value of the 'literal_block' key,
    with line breaks being preserved.

    The literal continues until de-dented, and the leading indentation is
    stripped.

        Any lines that are 'more-indented' keep the rest of their indentation -
        these lines will be indented by 4 spaces.
folded_style: >
    This entire block of text will be the value of 'folded_style', but this
    time, all newlines will be replaced with a single space.

    Blank lines, like above, are converted to a newline character.

        'More-indented' lines keep their newlines, too -
        this text will appear over two lines.

####################
# COLLECTION TYPES #
####################

# Nesting uses indentation. 2 space indent is preferred (but not required).
a_nested_map:
  key: value
  another_key: Another Value
  another_nested_map:
    hello: hello

# Maps don't have to have string keys.
0.25: a float key

# Keys can also be complex, like multi-line objects
# We use ? followed by a space to indicate the start of a complex key.
? |
  This is a key
  that has multiple lines
: and this is its value

# YAML also allows mapping between sequences with the complex key syntax
# Some language parsers might complain
# An example
? - Manchester United
  - Real Madrid
: [ 2001-01-01, 2002-02-02 ]

# Sequences (equivalent to lists or arrays) look like this
# (note that the '-' counts as indentation):
a_sequence:
- Item 1
- Item 2
- 0.5 # sequences can contain disparate types.
- Item 4
- key: value
  another_key: another_value
-
  - This is a sequence
  - inside another sequence
- - - Nested sequence indicators
    - can be collapsed

# Since YAML is a superset of JSON, you can also write JSON-style maps and
# sequences:
json_map: {"key": "value"}
json_seq: [3, 2, 1, "takeoff"]
and quotes are optional: {key: [3, 2, 1, takeoff]}

#######################
# EXTRA YAML FEATURES #
#######################

# YAML also has a handy feature called 'anchors', which let you easily duplicate
# content across your document. Both of these keys will have the same value:
anchored_content: &anchor_name This string will appear as the value of two keys.
other_anchor: *anchor_name

# Anchors can be used to duplicate/inherit properties
base: &base
  name: Everyone has same name

foo: &foo
  <<: *base
  age: 10

bar: &bar
  <<: *base
  age: 20

# foo and bar would also have name: Everyone has same name

# YAML also has tags, which you can use to explicitly declare types.
explicit_string: !!str 0.5
# Some parsers implement language specific tags, like this one for Python's
# complex number type.
python_complex_number: !!python/complex 1+2j

# We can also use yaml complex keys with language specific tags
? !!python/tuple [5, 7]
: Fifty Seven
# Would be {(5, 7): 'Fifty Seven'} in Python

####################
# EXTRA YAML TYPES #
####################

# Strings and numbers aren't the only scalars that YAML can understand.
# ISO-formatted date and datetime literals are also parsed.
datetime: 2001-12-15T02:59:43.1Z
datetime_with_spaces: 2001-12-14 21:59:43.10 -5
date: 2002-12-14

# The !!binary tag indicates that a string is actually a base64-encoded
# representation of a binary blob.
gif_file: !!binary |
  R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
  OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
  +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
  AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=

# YAML also has a set type, which looks like this:
set:
  ? item1
  ? item2
  ? item3
or: {item1, item2, item3}

# Like Python, sets are just maps with null values; the above is equivalent to:
set2:
  item1: null
  item2: null
  item3: null
{
  "data": {
    "sessionMaterial": {
      "id": "session-material:2018/tieto:databasis-json-yaml:1",
      "title": "YAML",
      "html": "\n          \n    \n\n    <h2>YAML</h2>\n<p>YAML is a data serialisation language designed to be directly writable and readable by humans.</p>\n<p>It&#x2019;s a strict superset of JSON, with the addition of syntactically significant newlines and indentation, like Python. Unlike Python, however, YAML doesn&#x2019;t allow literal tab characters for indentation.</p>\n<p>Install <strong>pyyaml</strong> package:</p>\n<div class=\"highlight\"><pre><code>pip install pyyaml</code></pre></div><p>Example Python script:</p>\n<div class=\"highlight\"><pre><code>import yaml\n\nsample_yaml_as_dict = &apos;&apos;&apos;\nfirst_dict_key: some value\nsecond_dict_key: some other value\n&apos;&apos;&apos;\n\nsample_yaml_as_list = &apos;&apos;&apos;\n- list item 1\n- list item 2\n&apos;&apos;&apos;\n\nmy_config_dict = yaml.load(sample_yaml_as_dict)\nprint(my_config_dict)\n\nmy_config_list = yaml.load(sample_yaml_as_list)\nprint(my_config_list)</code></pre></div><p>Output:</p>\n<div class=\"highlight\"><pre><code>python python_yaml.py\n{&apos;first_dict_key&apos;: &apos;some value&apos;, &apos;second_dict_key&apos;: &apos;some other value&apos;}\n[&apos;list item 1&apos;, &apos;list item 2&apos;]</code></pre></div><p>Example YAML file:</p>\n<div class=\"highlight\"><pre><code># Comments in YAML look like this.\n\n################\n# SCALAR TYPES #\n################\n\n# Our root object (which continues for the entire document) will be a map,\n# which is equivalent to a dictionary, hash or object in other languages.\nkey: value\nanother_key: Another value goes here.\na_number_value: 100\nscientific_notation: 1e+12\n# The number 1 will be interpreted as a number, not a boolean. if you want\n# it to be interpreted as a boolean, use true\nboolean: true\nnull_value: null\nkey with spaces: value\n# Notice that strings don&apos;t need to be quoted. However, they can be.\nhowever: &apos;A string, enclosed in quotes.&apos;\n&apos;Keys can be quoted too.&apos;: &quot;Useful if you want to put a &apos;:&apos; in your key.&quot;\nsingle quotes: &apos;have &apos;&apos;one&apos;&apos; escape pattern&apos;\ndouble quotes: &quot;have many: \\&quot;, \\0, \\t, \\u263A, \\x0d\\x0a == \\r\\n, and more.&quot;\n\n# Multiple-line strings can be written either as a &apos;literal block&apos; (using |),\n# or a &apos;folded block&apos; (using &apos;&gt;&apos;).\nliteral_block: |\n    This entire block of text will be the value of the &apos;literal_block&apos; key,\n    with line breaks being preserved.\n\n    The literal continues until de-dented, and the leading indentation is\n    stripped.\n\n        Any lines that are &apos;more-indented&apos; keep the rest of their indentation -\n        these lines will be indented by 4 spaces.\nfolded_style: &gt;\n    This entire block of text will be the value of &apos;folded_style&apos;, but this\n    time, all newlines will be replaced with a single space.\n\n    Blank lines, like above, are converted to a newline character.\n\n        &apos;More-indented&apos; lines keep their newlines, too -\n        this text will appear over two lines.\n\n####################\n# COLLECTION TYPES #\n####################\n\n# Nesting uses indentation. 2 space indent is preferred (but not required).\na_nested_map:\n  key: value\n  another_key: Another Value\n  another_nested_map:\n    hello: hello\n\n# Maps don&apos;t have to have string keys.\n0.25: a float key\n\n# Keys can also be complex, like multi-line objects\n# We use ? followed by a space to indicate the start of a complex key.\n? |\n  This is a key\n  that has multiple lines\n: and this is its value\n\n# YAML also allows mapping between sequences with the complex key syntax\n# Some language parsers might complain\n# An example\n? - Manchester United\n  - Real Madrid\n: [ 2001-01-01, 2002-02-02 ]\n\n# Sequences (equivalent to lists or arrays) look like this\n# (note that the &apos;-&apos; counts as indentation):\na_sequence:\n- Item 1\n- Item 2\n- 0.5 # sequences can contain disparate types.\n- Item 4\n- key: value\n  another_key: another_value\n-\n  - This is a sequence\n  - inside another sequence\n- - - Nested sequence indicators\n    - can be collapsed\n\n# Since YAML is a superset of JSON, you can also write JSON-style maps and\n# sequences:\njson_map: {&quot;key&quot;: &quot;value&quot;}\njson_seq: [3, 2, 1, &quot;takeoff&quot;]\nand quotes are optional: {key: [3, 2, 1, takeoff]}\n\n#######################\n# EXTRA YAML FEATURES #\n#######################\n\n# YAML also has a handy feature called &apos;anchors&apos;, which let you easily duplicate\n# content across your document. Both of these keys will have the same value:\nanchored_content: &amp;anchor_name This string will appear as the value of two keys.\nother_anchor: *anchor_name\n\n# Anchors can be used to duplicate/inherit properties\nbase: &amp;base\n  name: Everyone has same name\n\nfoo: &amp;foo\n  &lt;&lt;: *base\n  age: 10\n\nbar: &amp;bar\n  &lt;&lt;: *base\n  age: 20\n\n# foo and bar would also have name: Everyone has same name\n\n# YAML also has tags, which you can use to explicitly declare types.\nexplicit_string: !!str 0.5\n# Some parsers implement language specific tags, like this one for Python&apos;s\n# complex number type.\npython_complex_number: !!python/complex 1+2j\n\n# We can also use yaml complex keys with language specific tags\n? !!python/tuple [5, 7]\n: Fifty Seven\n# Would be {(5, 7): &apos;Fifty Seven&apos;} in Python\n\n####################\n# EXTRA YAML TYPES #\n####################\n\n# Strings and numbers aren&apos;t the only scalars that YAML can understand.\n# ISO-formatted date and datetime literals are also parsed.\ndatetime: 2001-12-15T02:59:43.1Z\ndatetime_with_spaces: 2001-12-14 21:59:43.10 -5\ndate: 2002-12-14\n\n# The !!binary tag indicates that a string is actually a base64-encoded\n# representation of a binary blob.\ngif_file: !!binary |\n  R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5\n  OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+\n  +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC\n  AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=\n\n# YAML also has a set type, which looks like this:\nset:\n  ? item1\n  ? item2\n  ? item3\nor: {item1, item2, item3}\n\n# Like Python, sets are just maps with null values; the above is equivalent to:\nset2:\n  item1: null\n  item2: null\n  item3: null</code></pre></div>\n\n\n        "
    }
  }
}