Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

yaml

Is it possible to have a list in the root section of an 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'

So in other words, is the list: section obsolete?

like image 453
Jan Schultke Avatar asked Apr 16 '16 10:04

Jan Schultke


People also ask

Which types of nodes are used in YAML to represent data structures?

Representation. YAML represents the data structure using three kinds of nodes: sequence, mapping and scalar.

How is a YAML file structured?

The basic structure of a YAML file is a map. You might call this a dictionary, hash or object, depending on your programming language or mood.

How do you define an array of objects in YAML?

An array is a group of similar values with a single name. In YAML, Array represents a single key mapped to multiple values. Each value starts with a hyphen - symbol followed by space. In a single line, write the same thing above using 'square brackets syntax.


2 Answers

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

org.yaml.snakeyaml.Yaml yaml = new org.yaml.snakeyaml.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 real scenario, we store an object content into yaml file. When we do that, if the type of one filed is List, we actually store like as you always see:

'field name':
- item1
- item2
like image 188
sel-fish Avatar answered Oct 04 '22 00:10

sel-fish


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.

like image 21
Anthon Avatar answered Oct 04 '22 02:10

Anthon