kimh
kimh

Reputation: 789

Multiple line key in YAML

Is it possible to have a multiple line key like this?

mykey:
  - >
    key
    one:
    keytwo: val

where keyone is treated as one key. I want to parse the yaml to yield:

{ mykey: [ { keyone: { keytwo: val } } ] }

Upvotes: 6

Views: 5578

Answers (1)

Jordan Running
Jordan Running

Reputation: 106017

You can have a multi-line key in YAML, but not quite in the way you describe. In a YAML mapping you can split the key and value onto separate lines by prefixing the key with ? and the value with :, like so:

? foo
: bar

The above would yield a data structure like { "foo": "bar" } in JSON. The YAML spec calls this an explicit key (whereas the usual foo: bar style is implicit). When you use the explicit style, the key can be any YAML data structure, including multi-line scalars:

mykey:
  - ? key
      one
    : keytwo: val

...but, like all multi-line scalars in YAML, even though lines are merged, one space will be preserved between the content of each line, so the above will result in a data structure like the following JSON:

{ "mykey":
  [ { "key one":
      { "keytwo": "val" }
    }
  ]
}

So you end up with key one instead of keyone, which isn't exactly what you wanted. But it's the closest you're going to get with YAML.

Upvotes: 13

Related Questions