vs YAML, Compared in Depth
Braces against indentation, with the type surprises and security traps tested.
JSON5 is JSON made comfortable to edit. YAML is a much larger language with indentation, anchors, tags, several string styles and more than one document per file. That power helps, and it also surprises.
Here the same inputs go through the yaml and js-yaml npm packages, PyYAML and the json5 package, so you can see where YAML 1.1 and 1.2 disagree, which converter output is safe, and when YAML is the better choice.
TL;DR: JSON5 types are visible in the syntax: strings are quoted, so NO cannot quietly become false. YAML offers reuse, multiple documents, block text and a huge ecosystem, but unquoted scalars are resolved differently by YAML 1.1 and 1.2 libraries. Use YAML where the tool demands it or those features pay off; use JSON5 for your own predictable config.
The Same Config Side by Side
YAML
# Service
service:
name: api
replicas: 3
ports:
- 80
- 443
env: &env
LOG_LEVEL: info
banner: |
Welcome.
Be kind.
debug: false
worker:
env: *envJSON5
// Service
{
service: {
name: 'api',
replicas: 3,
ports: [80, 443],
env: { LOG_LEVEL: 'info' },
banner: 'Welcome.\n\
Be kind.\n',
debug: false,
},
worker: {
env: { LOG_LEVEL: 'info' },
},
}We parsed both with yaml 2.9.1 and json5 2.2.3: the results were deeply equal. The two visible differences are reuse (YAML writes env once, JSON5 twice) and multi-line text (a YAML block scalar against a JSON5 string with a line continuation).
| Syntax | JSON5 | YAML 1.2 |
|---|---|---|
| Structure | {} and [] | Indentation, or {} and [] "flow" style |
| Comments | // and /* */ | # to end of line only |
| Unquoted text | Keys only, and only identifier names | Keys and values |
| Quotes | Single or double, same escapes | Double quotes process escapes; single quotes do not |
| Trailing comma | Allowed | Allowed in flow collections |
| Infinity and not-a-number | Infinity, NaN | .inf, .nan |
| Hexadecimal | 0x1F | 0x1F |
The quoting row bites during migration: in YAML, 'x\ny' is four characters with a literal backslash, while "x\ny" and the JSON5 string 'x\ny' contain a newline. A single quote inside YAML single quotes is doubled, as in 'it''s'.
Data Model Differences
A JSON5 document is one value: an object, array, string, number, boolean or null, arranged as a tree. The YAML 1.2.2 specification describes something bigger: a stream of documents, each a directed graph whose nodes carry tags and may be shared or even refer to themselves.
| Capability | JSON5 | YAML |
|---|---|---|
| Anchors and aliases (reuse a node) | ||
| Self-referencing structures | ||
| Type tags, including application tags | ||
| Several documents in one file | ||
| Block scalars for long text | ||
| Mapping keys that are lists or maps | Yes in the model; library support varies | |
| Duplicate keys | Allowed; the library keeps the last | Keys must be unique |
Library support really does vary. For the complex key ? [a, b] followed by : 1, yaml 2.9.1 turned the key into the string [ a, b ] with a warning, while js-yaml 5.5.0 threw "object-based map does not support complex keys". PyYAML 6.0.4 raised a ConstructorError for the unhashable list key. For duplicate keys, both JavaScript YAML libraries threw by default, PyYAML 6.0.4 safe_load silently kept the last value, and so did JSON5.parse.
Multiple documents
A line of three dashes starts a new document. Single-document APIs refuse such a file, which is the behavior RFC 9512 asks of applications that expect only one:
const text = '---\na: 1\n---\nb: 2\n';
yaml.parse(text); // throws: Source contains multiple documents
jsyaml.load(text); // throws: expected a single document
jsyaml.loadAll(text); // [ { a: 1 }, { b: 2 } ]
yaml.parseAllDocuments(text).map(d => d.toJS()); // same two objectsEmpty input differs too: yaml.parse('') returns null, js-yaml 5 throws (a change in 5.0.0), and JSON5.parse('') throws. For record streams in the JSON family, see JSON Lines.
Indentation Against Braces
In block YAML, spaces carry the structure. The specification forbids tab characters in indentation, because systems display them differently. In JSON5, whitespace never changes meaning, so a reformatter or a bad paste cannot move a key to another object. Braces cost some typing and catch some mistakes:
| YAML input | Result in yaml 2.9.1 and js-yaml 5.5.0 |
|---|---|
| A child line indented with a tab | Error |
A sibling indented one space too far after port: 80 | Error |
| A child accidentally moved to column one | No error: it becomes a top-level key |
msg: error: bad | Error: an unquoted value cannot contain a colon followed by a space here |
password: abc #123 | No error: the password is abc |
{a:1} | No error: one key named a:1 with a null value |
# intended: host belongs to server
server:
port: 80
host: example.com
# parsed: { server: { port: 80 }, host: 'example.com' }The silent cases are the dangerous ones. Quote any value containing # or :, and validate loaded configuration against a schema in either format; see schema validation.
Comments
YAML has only # comments, so commenting out a block means prefixing every line. JSON5 offers line and block comments, although block comments do not nest. Both formats discard comments when you load into plain objects. To keep them through a program edit in JavaScript, yaml provides parseDocument(), whose document nodes retain comments; its documentation notes that placement of some trailing comments can shift. In Python, ruamel.yaml advertises round-trip comment preservation. The json5 package has no comment-preserving writer.
YAML 1.1 vs 1.2 Type Surprises
The YAML specification's own history says YAML 1.0 appeared in early 2004, 1.1 in 2005 and 1.2 in 2009, with revision 1.2.2 in October 2021. The primary aim of 1.2 was to make YAML a strict superset of JSON, and it removed many problematic implicit typing rules. Libraries did not all move. PyYAML describes itself as a YAML 1.1 parser.
The difference is what an unquoted ("plain") scalar means. The YAML 1.1 boolean type accepts y, n, yes, no, on, off, true and false in several capitalizations. The 1.2 Core Schema accepts only true and false (lowercase, capitalized or uppercase).
The Norway problem
countries:
- DE
- FR
- NO
# 1.2 (yaml default, js-yaml default): ['DE', 'FR', 'NO']
# 1.1 (yaml {version: '1.1'}, js-yaml YAML11_SCHEMA, PyYAML):
# ['DE', 'FR', false]Norway's country code is a 1.1 boolean. The StrictYAML documentation explains the problem under that name. JSON5 cannot have this bug: an unquoted NO in value position is a syntax error, so the author is forced to write 'NO'.
One value, four readings
Each row is the document v: VALUE, run on November 29, 2026. "1.2" means yaml 2.9.1 and js-yaml 5.5.0 defaults. JSON5 reads the equivalent {v: VALUE}.
| Value | 1.2 | yaml in 1.1 mode | js-yaml YAML11_SCHEMA | PyYAML safe_load | JSON5 |
|---|---|---|---|---|---|
NO | "NO" | false | false | False | Error |
on | "on" | true | true | True | Error |
y | "y" | true | true | "y" | Error |
012 | 12 | 10 | 10 | 10 | Error |
0o12 | 10 | "0o12" | "0o12" | "0o12" | Error |
0x1F | 31 | 31 | 31 | 31 | 31 |
0b101 | "0b101" | 5 | 5 | 5 | Error |
1_000 | "1_000" | 1000 | 1000 | 1000 | Error |
22:22 | "22:22" | 1342 | 1342 | 1342 | Error |
1e3 | 1000 | 1000 | "1e3" | "1e3" | 1000 |
2026-11-29 | String | Date | Date | datetime.date | Error |
3.10 | 3.1 | 3.1 | 3.1 | 3.1 | 3.1 |
Null | null | null | null | None | Error |
| (empty) | null | null | null | None | Error |
22:22 becomes 1342 because 1.1 defines base-60 integers: 22 times 60 plus 22. A port mapping or a time of day can turn into a number. 3.10 losing its zero happens everywhere, JSON5 included: it is a number, so version strings need quotes in both formats. Note also that "YAML 1.1" implementations disagree with each other on y and 1e3.
Keys are resolved too
on: push
y: 1
# 1.2: { on: 'push', y: 1 }
# yaml 1.1 mode: error, Map keys must be unique
# js-yaml 1.1 schema: error, duplicated mapping key
# PyYAML: {True: 'push', 'y': 1}In the two JavaScript libraries' 1.1 modes, two keys that look different both became boolean true, hence the duplicate error. PyYAML converts only on. A %YAML 1.1 directive is not a portable fix either: yaml 2.9.1 honored it and read v: no as false, while js-yaml 5.5.0 with its default schema still returned the string. The reliable defenses are to quote every string that could be mistaken for something else, to load against an explicit schema, and to lint. RFC 9512 raises the same point: older syntax can make an implementation read {insecure: n} differently from what a 1.2 reader sees, and using the 1.2 boolean forms prevents it. The truthy rule of yamllint by default allows only true and false. To force strings in yaml, pass { schema: 'failsafe' }.
Anchors, Merge Keys and Tags
&name labels a node and *name repeats it. In both js-yaml and yaml the two places loaded as the same object, so changing one in memory changes the other. Many configs combine anchors with the merge key <<:
defaults: &d
adapter: postgres
host: localhost
dev:
<<: *d
database: app_dev
# 1.2 default: dev has two keys, a literal "<<" and database
# merge on: dev = { adapter, host, database }The merge key is a YAML 1.1 type definition, not part of the 1.2 Core Schema. Enable it deliberately: yaml.parse(text, { merge: true }), or in js-yaml 5 { schema: CORE_SCHEMA.withTags(mergeTag) }. PyYAML merges by default.
JSON5 has no equivalent. Do reuse in the program that loads the file, with an explicit base object and spread or a deep-merge function you control. That is more code and easier to trace.
Tags
Tags state a node's type: !!str, !!binary, or an application tag such as !Ref. Handling differs widely. For x: !Ref MyThing, yaml 2.9.1 warned that the tag was unresolved and returned the string, while js-yaml 5.5.0 threw "unknown scalar tag". For !!binary and !!set, yaml produced a Buffer and a Set; js-yaml rejected binary under its default schema and decoded it under YAML11_SCHEMA. A file that leans on tags is tied to the libraries that define them.
Block Scalars and Multi-line Strings
This is YAML's clearest advantage. Scripts, certificates and prose sit in the file almost verbatim. The indicator chooses how line breaks are treated, and the results below were identical in both JavaScript libraries:
| Header | Style | Source lines | Resulting string |
|---|---|---|---|
| | Literal, one final newline | line one, line two | "line one\nline two\n" |
> | Folded, lines joined by spaces | line one, line two | "line one line two\n" |
|- | Literal, strip final newline | x | "x" |
|+ | Literal, keep trailing blank lines | x and one blank line | "x\n\n" |
JSON5 strings may continue onto the next line with a final backslash. The continuation adds nothing to the value, so each real newline needs \n, and leading spaces on the next line become part of the string. It is workable for a short banner and tedious for a shell script. If long text dominates a file, keep it in separate files and reference them.
JSON5 Is Not Valid YAML, Even When It Parses
Both formats extend JSON in some sense, so people assume a YAML parser can read JSON5. YAML flow style does look similar: {a: 1, b: 'x', c: [1, 2,],} gave the same data under both parsers. Add one JSON5 comment and the result changes without an error:
const text = "{ a: 1, // c\n b: 'x', }";
JSON5.parse(text); // { a: 1, b: 'x' }
yaml.parse(text); // { a: 1, '// c b': 'x' }
jsyaml.load(text); // { a: 1, '// c b': 'x' }YAML does not know //, so both JavaScript libraries folded the comment text into the next key. PyYAML 6.0.4 rejected the same input with a ParserError. Always parse a .json5 file with a JSON5 parser. Strict JSON is much safer in a YAML parser, which is the 1.2 design goal, although the YAML rule that keys be unique rejects JSON with duplicate names, and RFC 9512 notes that flow-style YAML can look like JSON, so similar interoperability considerations apply. A 1.1 loader can also change types in valid JSON: js-yaml with YAML11_SCHEMA and PyYAML both read the JSON number 1e3 as a string.
Security
Unsafe loaders
Because tags can name types, some libraries historically let a document construct arbitrary objects, which means running code. RFC 9512 says such execution should be off by default.
| Advisory or release | What happened |
|---|---|
| CVE-2017-18342 (PyYAML) | Before 5.1, yaml.load() could execute arbitrary code on untrusted data |
| CVE-2020-14343 (PyYAML) | Before 5.4, full_load and FullLoader still allowed code execution |
| CVE-2022-1471 (SnakeYAML, Java) | Constructor() did not restrict instantiated types; NVD recommends SafeConstructor and version 2.0 or later |
| Psych 4.0.0 (Ruby) | Made safe loading the default for load |
In Python, call yaml.safe_load. With PyYAML 6.0.4, calling yaml.load without a Loader raises a TypeError, and safe_load refused a !!python/object/apply tag with a ConstructorError.
Alias expansion
RFC 9512 describes the "billion laughs" pattern: lists that alias lists that alias lists. We built a 396-byte document whose full expansion has 99, or 387,420,489, leaf values. It has nine lines: the first is a list of nine short strings, and each of the other eight lists the previous anchor nine times. The first two lines are:
a: &a ["l", "l", "l", "l", "l", "l", "l", "l", "l"]
b: &b [*a, *a, *a, *a, *a, *a, *a, *a, *a]| Loader and options | Result |
|---|---|
yaml 2.9.1, defaults (maxAliasCount 100) | Rejected: "Excessive alias count indicates a resource exhaustion attack" |
js-yaml 5.5.0, defaults (maxAliases is -1, no limit) | Loaded |
js-yaml 5.5.0, { maxAliases: 50 } | Rejected: "aliases exceeded maxAliases (50)" |
Loading is cheap in js-yaml because aliases share objects. The cost arrives when your code walks or serializes the result. For untrusted input set maxAliases, cap the input size, and count nodes before processing. js-yaml also limits nesting to 100 levels by default. Self-references are legal as well: both libraries loaded a: &r containing self: *r as a circular object, which JSON5.stringify then refuses with a TypeError.
What JSON5 avoids and what it does not
The format has no tags and no references, so a document cannot request a type or multiply itself. That removes two attack classes, not all risk. The JavaScript library had a prototype pollution flaw, CVE-2022-46175, fixed in 1.0.2 and 2.2.2, and in our test it accepted 200 nested arrays without complaint, so limit input size yourself. Never use eval as a parser. Details are in the security tutorial.
Tooling and Ecosystem
| Topic | JSON5 | YAML |
|---|---|---|
| Media type | application/json5 by convention, not registered with IANA | application/yaml, registered by RFC 9512 (February 2024) |
| Extension | .json5 | .yaml preferred, .yml still used |
JavaScript libraries (weekly npm downloads, November 22-28, 2026) | json5 2.2.3: 303,643,299 | js-yaml 5.5.0: 373,840,111; yaml 2.9.1: 311,146,368 |
Python | Third-party packages, see the Python guide | PyYAML (1.1), ruamel.yaml (1.2) |
| Safe style profile | The format is already small | KYAML for Kubernetes; yamllint |
Download totals cover every version and indirect install, not only the release named. js-yaml 5, released in June 2026, is a rewrite: safeLoad is gone, the default loader schema is the 1.2 Core Schema, and merge keys are off unless added. Code written for version 4 needs review.
KYAML: Kubernetes moves toward braces
Kubernetes documents KYAML, a stricter subset of YAML that uses flow style with braces and brackets and double-quotes all string values, to avoid whitespace and type coercion mistakes. The enhancement proposal, KEP-5295, lists alpha in v1.34, beta in v1.35 and stable in v1.37. We parsed the Pod example from its reference page, without the leading ---, with both JSON5.parse and a YAML parser, and got the same object. That is true of that sample, not a promise for all KYAML. See JSON5 and Kubernetes.
Conversion Code
YAML to JSON5
Decide the YAML version first: use the one the original consumer used, or the output changes meaning. This function defaults to 1.2, rejects errors, warnings (such as an unknown tag, which would otherwise be dropped), extra documents and excessive aliasing, then writes JSON5. A %YAML 1.1 directive inside the file overrides the version option:
// npm install yaml json5
const YAML = require('yaml');
const JSON5 = require('json5');
function yamlToJson5(text) {
const docs = YAML.parseAllDocuments(text, { version: '1.2', uniqueKeys: true });
for (const d of docs) {
const problems = [...d.errors, ...d.warnings];
if (problems.length) throw problems[0];
}
if (docs.length !== 1) {
throw new Error('expected one document, got ' + docs.length);
}
const data = docs[0].toJS({ maxAliasCount: 100 });
return JSON5.stringify(data, null, 2) + '\n';
}Comments are dropped, aliases are written out in full, merge keys stay literal unless you enable them, and a circular reference makes stringify throw. Review the diff, especially anything that became a date, a Set or a Buffer under tags or 1.1 rules.
JSON5 to YAML
The risk runs the other way here: an emitter may leave a string unquoted that another parser reads as a number or boolean. We serialized an object containing 'NO', 'on', '22:22', '012', '0o12', '1_000', '2026-11-29', '12e3', 'y' and Infinity, then read each output back with four loaders (yaml 1.2 and 1.1, js-yaml default and 1.1 schema), plus PyYAML:
| Emitter | Read back unchanged by |
|---|---|
yaml stringify, default 1.2 | The two 1.2 loaders only; 1.1 loaders and PyYAML altered values |
yaml stringify, version: '1.1' | The 1.1 loaders and PyYAML; the 1.2 loaders altered values |
js-yaml dump, default | All five |
// npm install js-yaml json5
const yaml = require('js-yaml');
const JSON5 = require('json5');
const json5ToYaml = (text) => yaml.dump(JSON5.parse(text));
console.log(json5ToYaml("{ countries: ['DE', 'NO'], flag: 'on', n: Infinity }"));
// countries:
// - DE
// - 'NO'
// flag: 'on'
// 'n': .inf (n is a boolean in YAML 1.1, so the key is quoted)That result covers the values we tested. Keep a round-trip assertion in your build using the parser that will consume the file. Browser-based options are on the conversion tools page.
When YAML Wins, and When It Does Not
Choose YAML when
- The platform requires YAML, as GitHub Actions workflow files do.
- Files hold scripts, templates or prose that benefit from block scalars.
- Repeated blocks are large and anchors keep them consistent.
- One file must carry several documents.
- You need a registered media type or comment-preserving editing libraries.
Choose JSON5 when
- A value's type should be obvious from how it is written.
- Your team already reads JSON and JavaScript.
- Copying and reindenting snippets must not change structure.
- Existing JSON files should remain valid as they are.
- You want a small grammar with no references or type tags.
For data passed between services, plain JSON usually beats both. See the main comparison, the TOML comparison, the JSONC comparison and the Hjson comparison.
Common Questions
Is JSON5 better than YAML?
It is more predictable, because its grammar is small and strings are quoted. YAML is more expressive. The tool that reads the file often settles the question.
Does YAML 1.2 fix the Norway problem?
In the 1.2 Core Schema, NO is a string. Libraries that still apply 1.1 rules, including PyYAML, read it as false, so quote it.
Can a YAML parser read JSON5?
Not reliably. Some flow-style text parses, but // comments can silently become part of a key.
Does JSON5 support anchors?
No. Compose shared settings in code, or generate the files from one source.
Which is safer for untrusted input?
JSON5 has fewer mechanisms to abuse. YAML can be used safely with a safe loader, alias limits and size limits. Both need validation after parsing.
Is JSON still valid YAML?
That was the main goal of YAML 1.2 and ordinary JSON loads fine. Documents with duplicate keys are an exception, since YAML requires unique keys.
Sources
(24)
- YAML Ain't Markup Language, revision 1.2.2
- YAML 1.1 boolean type
- YAML 1.1 integer type
- YAML 1.1 merge key type
- YAML 1.1 timestamp type
- RFC 9512: YAML Media Type
- GitHub Docs: Workflow syntax for GitHub Actions
- The JSON5 Data Interchange Format 1.0.0
- yaml library documentation
- js-yaml changelog
- js-yaml safety notes
- PyYAML documentation
- PyYAML on PyPI
- ruamel.yaml on PyPI
- StrictYAML: The Norway Problem
- yamllint truthy rule
- NVD: CVE-2017-18342
- NVD: CVE-2020-14343
- NVD: CVE-2022-1471
- NVD: CVE-2022-46175
- Psych 4.0.0 release notes
- Kubernetes: KYAML Reference
- KEP-5295 metadata
- npm download counts API
Last reviewed: November 29, 2026.
JavaScript
Python
TypeScript
Node.js
Rust
Java
C#
Ruby
Kotlin
Lua
Babel
Vite
webpack
ESLint
Prettier
VS Code
JetBrains