There's no need to introduce them: YAML and JSON have been the two star data formats for around twenty years. Both are used to represent structured data. We find them in configuration files, APIs, and many development tools.
At first glance, they allow us to do pretty much the same thing: store information as key-value pairs, organize objects, and manipulate lists. But then, why use YAML instead of JSON? And conversely, in which situations is JSON preferable?
Let's take a look at their differences with a few examples in this article.
What is JSON?
Well, let's introduce it, just in case an extraterrestrial happens to read this article. JSON (JavaScript Object Notation) is a text-based data format whose syntax is inspired by JavaScript. It was designed to represent and exchange structured data.
Here's an example of a JSON file:
{
"name": "My application",
"version": "1.0",
"debug": false,
"database": {
"host": "localhost",
"port": 3306
},
"extensions": [
"cache",
"logger"
]
}
JSON is based on a few simple data types:
- Strings.
- Numbers.
- Booleans (
trueandfalse). - The
nullvalue. - Objects.
- Arrays.
Its syntax is fairly strict: keys must be enclosed in double quotes, strings must also be enclosed in double quotes, and elements must be separated by commas.
This strictness has an advantage: JSON files are relatively easy to parse and their behavior is predictable.
What is YAML?
YAML (YAML Ain't Markup Language) is also a data representation format. It is particularly appreciated for its readability, especially in configuration files (Docker Compose, Kubernetes, ...).
Here is exactly the same information in YAML format:
name: My application
version: "1.0"
debug: false
database:
host: localhost
port: 3306
extensions:
- cache
- logger
We can immediately notice one difference: YAML uses indentation to represent the structure of data! There is no need to add braces, brackets, or commas. Quotes are also optional in many cases.
YAML also offers additional features, such as comments, anchors, aliases, and multiline strings.
YAML vs JSON: the main differences
Let's now compare the two formats across several aspects.
1. Readability
This is probably the most obvious difference.
JSON uses braces, brackets, commas, and quotes to represent data. For complex or nested structures, files can quickly become quite verbose.
YAML uses indentation and a lighter syntax. It is generally more pleasant to read when dealing with configuration files containing many parameters.
For example, a list in JSON:
{
"extensions": [
"cache",
"logger",
"database"
]
}
And the same list in YAML:
extensions:
- cache
- logger
- database
The result is identical, but YAML requires fewer characters. This simplicity comes at a cost, though. Incorrect indentation can completely change the structure of a YAML document.
2. Comments
JSON does not allow comments in a standard document. For example, the following is not valid JSON:
{
// Database configuration
"database": {
"host": "localhost"
}
}
YAML, on the other hand, allows us to add comments using the # character:
# Database configuration
database:
host: localhost
This is particularly useful for documenting application settings directly in their configuration file.
3. Data types
Both formats support the main data types: strings, numbers, booleans, null values, objects, and lists.
However, YAML has a richer type system. For example, YAML allows us to explicitly represent certain types using tags:
enabled: !!bool true
count: !!int 42
price: !!float 19.99
It also supports dates and timestamps, depending on the type resolution rules used by the parser.
JSON is more limited and stricter in this respect. It only has six data types: string, number, boolean, null, object, and array.
However, we need to be careful with YAML: some values can be interpreted differently from what we might expect.
For example:
enabled: yes
Depending on the YAML version and the library being used, yes may be interpreted as a boolean or as a string. YAML 1.2 notably aligned boolean values with true and false.
To avoid surprises, it's better to explicitly use true and false.
4. Multiline strings
YAML offers several syntaxes for representing multiline strings. For example, using the | character:
description: |
This is a description
that spans multiple lines.
Line breaks are preserved in the value. We can also use the > character to fold lines:
description: >
This is a description
that spans multiple lines.
Line breaks are then generally replaced with spaces.
In JSON, we need to use the \n escape character:
{
"description": "This is a description\nthat spans multiple lines."
}
YAML is therefore more convenient when working with long texts, particularly in configuration files.
5. Anchors and aliases
This is an interesting YAML feature: anchors and aliases allow us to reuse data blocks without having to copy them.
For example:
database: &database
host: localhost
port: 3306
username: app
development:
database:
<<: *database
host: 127.0.0.1
production:
database:
<<: *database
host: db.example.com
The &database anchor defines a reusable block. The *database alias allows us to reference it elsewhere.
The << operator allows us to integrate the keys from the referenced block into another mapping.
JSON does not offer an equivalent mechanism. We have to repeat the data or handle this reuse directly in our code.
6. Syntax and errors
JSON has a strict syntax. A missing comma, a key without quotes, or a missing brace makes the document invalid.
YAML, on the other hand, is more permissive in some respects, but that doesn't mean it's easier to parse.
Indentation is particularly important: just two extra spaces can be enough to change the structure of a document.
Another particularity is that YAML accepts several syntaxes for representing certain values. This can sometimes make files less predictable, especially when multiple libraries or versions of the format are used.
JSON is generally easier to validate and handle consistently across different languages.
Performance: YAML or JSON?
In terms of performance, JSON generally has an advantage. Its syntax is simpler, and JSON parsers are widespread and often particularly well optimized.
YAML requires a more complex parser, notably because of its many features: indentation, anchors, aliases, tags, and different string styles.
YAML parsing can therefore be slower than JSON parsing, although this depends heavily on the library being used and the size of the files.
In most applications, this difference won't matter. For a few configuration files, parsing time will generally be negligible. However, if we're exchanging large amounts of data between several services, JSON is often a more suitable choice.
When should we use YAML or JSON?
As is often the case, there is no universal answer. Both formats have their advantages, and the choice mainly depends on the intended use.
YAML is particularly interesting for:
- Configuration files.
- Docker Compose files.
- Kubernetes manifests.
- CI/CD pipelines.
- Files that require comments.
- Relatively complex configurations with reusable blocks.
JSON is generally preferable for:
- REST APIs.
- Data exchanges between applications.
- JavaScript applications.
- Data stored or transmitted automatically.
- Situations where compatibility between languages is important.
Of course, these are not absolute rules. We can perfectly well use JSON for a configuration file or YAML to represent data exchanged between two applications.
Converting YAML to JSON and vice versa
Good news: YAML and JSON are similar enough to make it easy to convert documents from one format to another. For example, using Python and the PyYAML library:
import json
import yaml
with open("config.yaml", "r") as file:
data = yaml.safe_load(file)
json_content = json.dumps(data, indent=4)
print(json_content)
In the other direction, we can use json.load() to read a JSON file, then yaml.dump() to generate YAML:
import json
import yaml
with open("config.json", "r") as file:
data = json.load(file)
yaml_content = yaml.dump(data, sort_keys=False)
print(yaml_content)
We can also perform these conversions directly from our browser:
Conclusion
YAML and JSON allow us to represent the same broad categories of data, but they don't meet exactly the same needs.
It's up to us to make the right choice!