Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an empty string a valid YAML document?

Tags:

yaml

  • I have a library returning no document on loading an empty string (''), and I wonder whether this is a bug.
  • I was not able to infer from the YAML 1.2 specification (most recent as of asking this question) whether the empty string is a valid YAML document.
  • Various (online) YAML validators require at least one character to show a result, e.g. YAMLValidator.com, or OnlineYAMLTools.com.
  • YAMLLint.com accepts an empty string as input, but changes the input text to --- false upon validation, raising the question whether the empty string was actually the input.

So, in general, is an empty string a valid YAML document?

like image 679
Max Avatar asked Oct 31 '25 09:10

Max


1 Answers

A YAML file is parsed as a YAML stream by the parser. A YAML stream can contain multiple documents. The definition of this stream in the spec is as follows:

l-yaml-stream ::= l-document-prefix* l-any-document?
                  ( l-document-suffix+ l-document-prefix* l-any-document?
                  | l-document-prefix* l-explicit-document? )* 

As you can see, since both l-document-prefix and l-any-document are optional, an empty YAML stream is valid – but contains no document.

If you're asking whether l-any-document can produce the empty string, the answer is no. Without a starting ---, you have an l-bare-document which must contain at least one node. A plain scalar is produced by ns-plain(n,c) and if you descend in there, you will notice that it must contain at least one character produced by ns-plain-first(c).

If you want to have a YAML stream containing one document which contains an empty scalar as root node, you have the following options:

  • empty quoted scalars ("" or '') – best if you want the scalar to load as string, since a non-quoted empty scalar should be resolved to !!null as per the schema defined in the spec.
  • explicit document (---). Since the document is explicitly started with the directives end marker, it is allowed to have no content, which is interpreted as empty scalar at top level.
  • explicit document with tag (--- !!str) ensures that the empty scalar is loaded as string.

Edit: A note on that YAMLlint site: Don't use it. It doesn't tell you which implementation it's using, which YAML version it expects etc. Its output indicates that it parses the empty input as single document with an empty scalar, and parses that scalar as the boolean value false. While this is allowed by the spec (since the spec does not force any specific schema upon an implementation), it does not conform to any official scheme.

like image 179
flyx Avatar answered Nov 03 '25 13:11

flyx