Jan Schultke
Jan Schultke

Reputation: 39648

Is it possible to have a list in the root section?

Is it possible to have a list in the root section of a YAML file? So far I've seen no files that follow such a structure and I've been asking myself whether it violates the syntax.

Here is an example:

- 'entry A'
- 'entry B'
- 'entry C'

What I've seen so far:

list:
  - 'entry A'
  - 'entry B'
  - 'entry C'

In other words, is the list: section obsolete?

Upvotes: 18

Views: 14485

Answers (2)

sel-fish
sel-fish

Reputation: 4476

It's ok to do that.
Here is a Java sample which use snakeYaml:

Yaml yaml = new Yaml();
Object o = yaml.load("- 'entry A'\n- 'entry B'\n- 'entry C'");
System.out.println(o.getClass().getName());

The output of the code is java.util.ArrayList.

But in a real scenario, we store an object's content into a YAML file. When we do that, if the type of one field is a list, we actually store it in the way as you always see:

field-name:
- item1
- item2

Upvotes: 13

Anthon
Anthon

Reputation: 76614

No the the scalar list is not obsolete, it defines a completely different structure.

YAML files consist of mappings, sequences and scalars.

  • A mapping consists of key-value pairs. A key can be scalars or a list; a value can be a mapping or a sequence or a scalar.
  • A list consists of elements and each element can be a mapping, a sequence or a scalar
  • A scalar is in principle a string, but certain strings can be interpreted specially ( numbers only -> integers, "False" -> boolean, etc.)

At the top level you can have a (single) scalar (admittedly this is not very flexible):

Hello world

or a mapping:

abc: 
  - 1
  - 2

or a a list:

- 1
- 2  

Your first example has at the top level a sequence consisting of scalars, your second example has at the top level a mapping with a single key-value pair. The key being the scalar list and value being a sequence of scalars.

Upvotes: 8

Related Questions