All articles

YAML vs JSON: differences and when to use each

· 3 min read

JSON and YAML can represent the same data: objects, arrays, strings, numbers, booleans and null. They're designed for different readers. JSON is strict and simple, which makes it ideal for machines exchanging data. YAML is designed to be written and read by people, which makes it popular for configuration, at the cost of a much more complicated specification.

The same data in both

{
  "service": "api",
  "replicas": 3,
  "env": { "LOG_LEVEL": "info", "FEATURE_X": true },
  "ports": [8080, 9090]
}
# API deployment settings
service: api
replicas: 3
env:
  LOG_LEVEL: info
  FEATURE_X: true
ports:
  - 8080
  - 9090

The differences

JSON YAML
Structure Braces and brackets Indentation
Comments Not allowed # comment
Strings Always double-quoted Quotes usually optional
Multi-line strings \n escapes Block scalars (| and >)
Reuse None Anchors and aliases (&base, *base)
Multiple documents per file No Yes, separated by ---
Spec size A few pages Over 80 pages
Native support JSON.parse everywhere Needs a library

YAML 1.2 is a superset of JSON, so you can paste JSON into a YAML file and it still parses.

YAML's type surprises

Unquoted values in YAML are typed by their content. That's convenient until a value means something you didn't intend. The behavior also depends on the YAML version your parser follows.

country: NO
enabled: yes
mode: 0755
version: 1.10
zip: 01234
time: 12:30

What two common parser behaviors produce:

Key YAML 1.2 (e.g. yaml for JavaScript) YAML 1.1 (e.g. PyYAML)
country: NO "NO" false
enabled: yes "yes" true
mode: 0755 755 493 (octal)
version: 1.10 1.1 1.1
zip: 01234 1234 668 (octal)
time: 12:30 "12:30" 750 (base 60)

The first row is the famous "Norway problem": the country code for Norway becomes false. In both versions, 1.10 becomes the number 1.1 and leading zeros are lost.

The fix is simple: quote strings that look like other types. Version numbers, ZIP codes, country codes, times and anything like yes, no, on or off should be in quotes.

Security: don't load untrusted YAML with full features

Some YAML loaders can construct arbitrary objects from tags like !!python/object. Loading untrusted YAML with them can execute code:

  • Python: use yaml.safe_load, never yaml.load with the full or unsafe loader.
  • Ruby: use YAML.safe_load.
  • JavaScript: yaml and js-yaml (v4) don't create arbitrary objects by default.

Aliases can also be abused: a tiny file with nested aliases can expand into gigabytes of data (the "billion laughs" attack). Good libraries limit alias expansion.

Which to choose

Use JSON for:

  • API requests and responses.
  • Data stored or exchanged between programs.
  • Anything generated by code, where nobody edits it by hand.
  • Browser code, where JSON.parse is built in.

Use YAML for:

  • Configuration people edit and review: Kubernetes manifests, GitHub Actions, Docker Compose, Ansible, OpenAPI specs.
  • Files that benefit from comments explaining why a setting exists.
  • Long multi-line strings like scripts and templates.

Consider alternatives when YAML's ambiguity is a problem: TOML for flat config, or JSON with a schema and an editor that validates it.

Converting between them

JavaScript, with the yaml package:

import YAML from "yaml";

const yamlText = YAML.stringify(JSON.parse(jsonText));
const data = YAML.parse(yamlText);

YAML.stringify quotes strings that would otherwise be read as another type, such as "1.10". Comments can't survive a round trip through JSON, since JSON has nowhere to keep them.

Python:

import json, yaml

yaml_text = yaml.safe_dump(json.loads(json_text), sort_keys=False)
data = yaml.safe_load(yaml_text)

Command line, with yq:

yq -p=json -o=yaml '.' config.json > config.yaml   # JSON to YAML
yq -p=yaml -o=json '.' config.yaml                 # YAML to JSON

Validating

Because YAML is so permissive, a typo often produces valid YAML with the wrong structure: a list item that became a string, or a key nested one level too deep. Validate config against a JSON Schema (most YAML tools accept one), and see common YAML errors for the mistakes that cause parse failures. The JSON Schema guide shows how to write the schema.

Frequently asked questions

Is every JSON file valid YAML?

Practically yes for YAML 1.2, which was designed as a JSON superset. A few edge cases differ, such as very long keys and some escape sequences, but normal JSON parses as YAML.

Can JSON have comments?

Standard JSON can't. JSONC (used by VS Code and tsconfig.json) and JSON5 allow them, but strict JSON parsers reject them.

Which is faster to parse?

JSON, by a wide margin, because its grammar is far simpler and parsers are built into every runtime. For config files the difference rarely matters.

What about TOML?

TOML is another human-friendly config format, used by Cargo and pyproject.toml. It's less ambiguous than YAML but awkward for deeply nested data.

Further reading