Polymerase
Polymerase

Reputation: 6811

Rule governing sequence of fields in a YAML

Checking the validity of a YAML using https://onlineyamltools.com/convert-yaml-to-json

The below YAML is correct

# Valid yaml (field "name" placed at LAST position)
match:
- uri:
    prefix: "/mysvc1/"
route:
- destination:
    host: myservice1
    port:
        number: 80
name: "svc1-routes"

However, if I move the field name to first position, the YAML becomes invalid. What is the reason?

# Invalid yaml (field "name" placed at FIRST position)
match:
name: "svc1-routes" # <---- ERROR ----
- uri:
    prefix: "/mysvc1/"
route:
- destination:
    host: myservice1
    port:
        number: 80

The error message:

Error: YAMLException: end of the stream or a document separator is expected at line 4, column 1:
    - uri:
    ^

Upvotes: 0

Views: 1538

Answers (1)

flyx
flyx

Reputation: 39738

In contrary to your comment, name and match are on the same level because they share the same indentation. name is in no way nested in match (nor is route).

The list items, however, are nested in match since YAML understands the - as parts of the indentation, hence the list items are considered more indented than match and are thus nested in it.

Concerning your error:

name: "svc1-routes"
- uri:

In this part, the mapping key name is assigned the scalar value svc1-routes. Each mapping key may only have one value. On the next line, a sequence starts which is on a deeper indentation level (as explained above) but YAML can't put it anywhere because the key name already has a value. This is why it issues an error.

You can freely switch the mapping keys together with their nested values, e.g.:

route:
- destination:
    host: myservice1
    port:
        number: 80
name: "svc1-routes"
match:
- uri:
    prefix: "/mysvc1/"

This will load to the same structure as per YAML spec.

Upvotes: 1

Related Questions