JSON vs YAML: which one should you use?

Both formats describe the same data. Here is how they differ in syntax, tooling and risk, and a simple rule for choosing between them.

Basics By Convert JSON to YAML Team

JSON vs YAML: which one should you use?

JSON and YAML can describe exactly the same data: objects, lists, strings, numbers, booleans and null. YAML 1.2 is even a superset of JSON, which means every valid JSON document is already valid YAML. So why do both exist, and when should you pick one over the other?

The same data, two ways

{
  "service": "api",
  "replicas": 3,
  "ports": [80, 443],
  "env": { "DEBUG": false }
}
service: api
replicas: 3
ports:
  - 80
  - 443
env:
  DEBUG: false

JSON marks structure with braces, brackets and commas. YAML uses indentation and dashes, which removes most of the punctuation and makes the file easier to scan.

Where JSON wins

  • Strictness. There is one way to write a string and one way to write a list. Parsers agree with each other.
  • Speed and ubiquity. Every language ships a fast JSON parser, and browsers parse it natively.
  • Safety for machines. There are no indentation rules, so generated output cannot be broken by whitespace.

Use JSON for APIs, message payloads, logs, storage and anything produced and consumed mainly by programs.

Where YAML wins

  • Readability. Less punctuation and no quotes around most strings.
  • Comments. You can explain why a value is set, which JSON does not allow.
  • Multi-line text. Block scalars keep scripts and certificates readable.
  • Reuse. Anchors and aliases let you define a block once and reference it elsewhere.
  • Multiple documents. One file can hold several documents separated by ---.

Use YAML for configuration that people edit by hand: Kubernetes manifests, Docker Compose files, GitHub Actions workflows, Ansible playbooks and OpenAPI specs.

The risks to know about

The flexibility of YAML has a cost. Unquoted values are guessed: no can become a boolean, 1.10 becomes the number 1.1, and 007 may turn into 7. Indentation mistakes change the structure silently. A good converter quotes ambiguous strings for you, which is exactly what our converter does by default.

A simple rule

SituationFormat
Programs talk to programsJSON
People edit the fileYAML
You need commentsYAML
You need maximum parser compatibilityJSON

When you receive JSON but your tool expects YAML, convert it rather than rewriting it by hand. It is faster, and it avoids the quoting and indentation mistakes described above.

← Blog