blog.stogas.dev

JSON is YAML

 •  • Updated:  • small-tips, devops, development

I've read that "YAML is a superset of JSON", but I never truly understood what that means.

Sure, when you think about it, YAML and JSON can both represent the same structured data in different formats. Maybe it means YAML supports more data types or handles more edge cases?

No - it literally means that JSON is valid YAML!

Well, most of the time, at least.

{
  "name": "Acme Corp",
  "employees": 150,
  "is_private": true,
  "locations": [
    "New York",
    "London"
  ]
}
  • Is this JSON? Yes!
  • Is this YAML? Yes!

What do you mean? #

No - it literally means that JSON is valid YAML: https://en.wikipedia.org/wiki/YAML#JSON

Put another way, JSON is just a stricter subset of YAML. All JSON documents obey YAML's rules (plus some extra ones), so any JSON file is valid YAML too.

In plain English: take the full YAML specification, add a few constraints (e.g. no comments, mandatory quoting in certain cases, mandatory square brackets, etc.), and you’ve got JSON.

Block style vs. flow style #

YAML supports two equivalent syntaxes for collections:

Block style YAML (the more common, more human-readable YAML form) uses indentation and dashes:

some_list:
  - item1
  - item2

Flow style (JSON-like) uses brackets and commas (still YAML):

some_list: ["item1", "item2"]

You can even quote the key, which is still valid YAML:

"some_list": ["item1", "item2"]

Finally, in YAML you're allowed to quote the key and use flow style, along with making the top-level structure either an object or an array.

All of these rules are strictly enforced in JSON, but also allowed in YAML.

This is now not only YAML, but JSON at the same time:

{
  "some_list": ["item1", "item2"]
}

Read more about this here: https://en.wikipedia.org/wiki/YAML#JSON

How is this useful? #

One real life example: JSON does not allow comments. While JSONC exists, it's not supported everywhere.

This very blog (written in Hugo) does not support JSONC. If I want to display JSON with comments, it looks like this:

{
  "happy": false # this comment is invalid
}

But, simply use the yaml tag instead of json in the markdown codeblock, and suddenly it renders completely fine - JSON is valid YAML, and YAML allows comments:

{
  "happy": false # this comment is invalid
}

KYAML #

Whether you agree with the idea or not, Kubernetes also released KYAML, a kind of in-between of JSON and YAML. It too is valid YAML!