JSON and YAML can represent the same data: objects (maps), arrays (lists), strings, numbers, booleans and null. In fact, YAML 1.2 is a superset of JSON, so any valid JSON document is also valid YAML. The difference is in who they are designed for. JSON is strict and easy for machines to produce and parse. YAML is easier for people to read and write, at the cost of more rules and more surprises.
| JSON | YAML | |
|---|---|---|
| Primary use | APIs, data exchange, storage | Configuration files (CI, Kubernetes, Docker Compose) |
| Comments | Not supported | # comments supported |
| Structure | Braces and brackets | Indentation |
| Strings | Always double-quoted | Quotes usually optional |
| Typing | Explicit | Implicit, which can surprise you |
| Parsers | Built into every language | Separate library, more complex |
| Multi-document files | No | Yes, separated by --- |
JSON:
json{ "service": "api", "port": 8080, "enabled": true, "tags": [ "prod", "us-east-1" ] }
YAML:
yamlservice: api port: 8080 enabled: true tags: - prod - us-east-1
The YAML version is shorter and has no punctuation noise, which is why people prefer it for files they edit by hand.
Implicit typing. YAML guesses types from how a value looks. Under YAML 1.1 rules, which many parsers still follow, no, off and yes become booleans. That's the well-known "Norway problem", where the country code NO turns into false:
yamlcountry: NO # parsed as false by YAML 1.1 parsers version: 1.10 # parsed as the number 1.1 zip: 01234 # may be parsed as an octal number
Quote values that must stay strings: country: "NO", version: "1.10".
Indentation is structure. A single misplaced space changes which object a key belongs to, and tabs aren't allowed for indentation at all.
Many ways to write strings. Block scalars (| and >), single quotes and double quotes all behave differently with line breaks and escapes.
JSON.parse is built in and fast.Because JSON is valid YAML, converting JSON to YAML never loses data. Going the other way, you lose comments, and you need to watch for values whose type YAML guessed differently than you intended. After converting YAML to JSON, check the types of anything that looks like a boolean, a version number or a code with leading zeros.
To catch structural mistakes in either format, validate the result against a schema; see JSON Schema basics. Many YAML tools, including Kubernetes and editors with the YAML language server, use JSON Schema for this.