Should I quote Strings in YAML?

Should I or should I not? Is it required? Will it work even without quotes – single or double?

ANSWER

I’ve asked myself these questions several times. Often I end up double-quoting long strings, but not for one word ones or shorter strings. Which makes it rather inconsistent. Especially if that string contains characters like a forward slash, a colon or semi-colon. Like when you have a URL as a value. I suppose it’s out of habit.

Thing is, it is not required. Strings can be quoted or not. There is no difference. It will still work with or without it. Even with spaces in that string. YAML allows it. Below are 2 examples:

phrase: 'The quick brown fox jumps over the lazy dog.'
poem: "Hey, diddle, diddle. The cat and the fiddle. The cow jumped over the moon."

The key part of the key-value pair can also be quoted too. The YAML won’t error out. Again, it’s allowed. So this is valid:

'foo':
  "bar": foobar

Single quote or double quotes don’t matter. It can be mixed. Above examples are both acceptable.

However, not quoting is not true in all cases. There are certain instances when it is required such as when there is a colon in the key. In this case, the key needs to be quoted.

'key:': value

What about quotes in the value itself?

CORRECT - phrase1: 'The quick ''brown'' fox jumped over the lazy dog.'
WRONG- phrase2: "The quick ""brown"" fox jumped over the lazy dog."
CORRECT - phrase3: "The quick \"brown\" fox jumped over the lazy dog."
WRONG - phrase4: "The quick '"brown"' fox jumped over the lazy dog."
CORRECT - phrase6: The quick 'brown' fox jumped over the lazy dog.
CORRECT - phrase7: The quick "brown" fox jumped over the lazy dog.

Finally, what does YAML mean?

It is short for – YAML Ain’t Markup Language.