1

I am wondering if it is possible to fold YAML keys into single line.

Like to transform:

lvl1:
  lvl2:
    lvl3:
      lvl4:
        key1: val1
        key2: val2

into something like:

lvl1.lvl2.lvl3.lvl4:
  key1: val1
  key2: val2

I see such syntax in Java Spring Framework config files.

gavenkoa
  • 45,285
  • 19
  • 251
  • 303

1 Answers1

2

Well you can write this as it's valid YAML. However it will make lvl1.lvl2.lvl3.lvl4 a single key. If you want to write your YAML like this, you'll need to implement post-loading logic to transform it into the original structure.

In Spring, dotting the levels together works because

The YamlPropertiesFactoryBean will load YAML as Properties

Properties in Java are a list of key-value pairs, so nested mappings are transformed into a list of keys where each key incorporates its path from the document root. Your transformed YAML would look like this:

lvl1.lvl2.lvl3.lvl4.key1=val1
lvl1.lvl2.lvl3.lvl4.key2=val2

This result is identical for both your original and the condensed YAML file, which is why you can do this in Spring config files. However, it is not a feature of YAML itself.


A format that uses condensed dotted notation is TOML:

[lvl1.lvl2.lvl3.lvl4]
key1 = "val1"
key2 = "val2"

Above document yields the same structure as your original YAML file.

flyx
  • 35,506
  • 7
  • 89
  • 126