What is YAML and what’s it for?

yamlWhen you work with data on the modern web, you mostly likely work with JSON. Almost every web service offers a data stream in JSON, which has significant advantages over its predecessor, XML. With JSON, a simple JSON.parse() statement converts a data string to a JavaScript object, and from there accessing and manipulating the data with your code is fairly straightforward. Despite this ease of use, though, JSON doesn’t stand alone when it comes to exchanging data on the web today. Some sources still make XML available, either because they’re dated, or because they’re in a sector whose consumers expect XML. However, a smattering of other data formats are also part of the modern web, and it’s useful to become familiar with them. Once you have a working knowledge of JSON, one of the easiest related formats to get under your belt is YAML.

Recursively named YAML Ain’t Markup Language, YAML is a superset of JSON. This means that any valid JSON is also valid YAML, and an app that expects YAML can consume JSON without missing a beat. However, YAML supports features that JSON doesn’t, such as comments, so valid YAML can’t be used interchangeably with JSON.

One of the biggest differences between YAML and JSON — and one of the driving forces behind the creation of YAML — is that YAML is designed to be human readable. To achieve this, in addition to supporting comments, the language treats white space as significant. For instance, indenting multiple lines of data implicitly marks those lines as a block. Other aspects of the language enable you to encode data objects such as arrays without the enclosing and delimiting characters used in JSON. In fact, if you’ve ever worked with Markdown, YAML should look very familiar, as both YAML and Markdown have quite a bit of syntax in common.

Because JavaScript includes built-in support for converting between JSON strings and JavaScript objects, JSON is slightly easier to work with in a JavaScript app than YAML. However, compact libraries to convert between YAML and JSON are available and easy to use. Perhaps the most popular is yaml.js.

Check out my recently released course, Processing and Interchanging JSON Data on Lynda.com (subscription required), for more about working with JSON, including converting between JSON and YAML and between JSON and XML.

Basic components of YAML (Wikipedia)

yaml.js (GitHub)

Processing and Interchanging JSON Data (Lynda.com)