YAML versus JSON

How YAML and JSON differ in syntax, data types, comments and conversion, which one suits each job, and what breaks when you copy, paste or convert between them.

YAML and JSON can describe the same structured data: key-value maps, ordered lists, strings, numbers, booleans and null. They differ in how that data is written, how much the format infers from what you type, and which features survive when you convert from one to the other. This guide covers what changes between the two, how to choose for a given job, and how to check that the output still works where you need it.

What changes when data moves between YAML and JSON

Converting between the formats changes the syntax that represents the data. It does not have to change the data itself. JSON marks structure with braces, brackets, commas and double quotes. YAML marks the same structure mostly with indentation, dashes and colons. Converting a plain map of strings and numbers from one format to the other gives an equivalent structure. Conversion becomes lossy when the source uses features the target format has no way to express. That happens mostly when going from YAML to JSON.

The same data in both formats

The two snippets below were written by hand to represent identical data. They are illustrative and are not the observed output of any particular converter. A converter may choose different quoting, indentation or key order.

{
  "service": "api",
  "replicas": 3,
  "debug": false,
  "ports": [8080, 8443],
  "owner": null
}
# Comments are allowed in YAML
service: api
replicas: 3
debug: false
ports:
  - 8080
  - 8443
owner: null

Core syntax differences

  • Structure: JSON uses braces, brackets and commas, so whitespace outside strings has no meaning. YAML block style uses indentation to show nesting, and tabs are not allowed for indentation.
  • Quoting: JSON strings must be in double quotes. YAML usually lets you leave strings unquoted and infers the type from how the value looks.
  • Comments: JSON has no comment syntax. YAML supports comments that start with #.
  • Trailing commas: JSON forbids them. YAML block style has no commas to get wrong.
  • Multiline text: JSON needs escape sequences such as \n inside one string. YAML offers literal (|) and folded (>) block scalars that keep text readable across lines.
  • Reuse: YAML anchors (&) and aliases (*) let one node be referenced again elsewhere. JSON has no equivalent.
  • Multiple documents: one YAML stream can hold several documents separated by ---. Standard JSON holds one value per text.
  • Flow style: YAML also accepts JSON-like inline syntax, such as {a: 1} and [1, 2], so you can mix styles in one file.

What does not survive YAML-to-JSON conversion

  • Comments are dropped, because JSON cannot store them.
  • Anchors and aliases are expanded into repeated copies, so the link between them is lost.
  • Custom tags and language-specific types either fail to convert or turn into plain values, depending on the tool.
  • A multi-document YAML stream must be split into separate JSON files or wrapped in an array.
  • Non-string keys, such as numbers, booleans or complex keys, must be turned into strings or rejected, because JSON object keys are always strings.
  • Formatting choices such as quoting style, block scalars and key layout are not preserved. Converting back to YAML will not reproduce the original file.

Going from JSON to YAML is usually safe for the data, because YAML 1.2 was designed so that JSON text is almost always valid YAML. There are edge cases. YAML requires mapping keys to be unique, while the JSON specification only says keys should be unique. A JSON document with duplicate keys can therefore be rejected or handled differently by a YAML parser.

Which format suits your intended result

Criterion | JSON | YAML
Primary strength | Strict, simple, unambiguous data interchange | Human-friendly authoring and editing
Comments | Not supported | Supported with #
Whitespace | Not significant outside strings | Indentation is significant
Type inference | None; types are explicit in the syntax | Unquoted values are interpreted, which can surprise you
Reuse within a file | Not supported | Anchors and aliases
Multiline strings | Escaped within one line | Literal and folded block scalars
Specification size | Small grammar | Much larger specification with several versions in use
Parser consistency | Generally consistent across libraries | Varies with the YAML version and library defaults
Round-trip to the other format | JSON to YAML is generally lossless for data | YAML to JSON can lose comments, anchors, tags and documents
Typical fit | APIs, logs, machine-generated data, browser contexts | Configuration files, deployment manifests, CI definitions

Choose JSON when programs produce and consume the data, when you need every parser to read it the same way, or when the data crosses a network or a language boundary. The strict syntax makes errors easy to detect, and the lack of type inference means a value is exactly what it appears to be.

Choose YAML when people write and review the file by hand, when comments explaining settings matter, or when long text blocks and repeated sections would be awkward in JSON. The tradeoff is a larger and more permissive syntax. Small indentation or quoting mistakes can produce a different valid document instead of an error.

A common mixed workflow is to author in YAML, validate it, and convert to JSON for systems that need strict input. Many schema tools, including JSON Schema validators, can check data parsed from either format, because what they validate is the parsed structure and not the text.

Implicit typing pitfalls in YAML

Because YAML infers types from unquoted values, the parser can change what you meant. The rules depend on the YAML version. YAML 1.1 treats words such as yes, no, on and off as booleans and reads numbers with a leading zero as octal. The YAML 1.2 core schema recognizes only true and false as booleans and writes octal with a 0o prefix. Some widely used libraries still follow YAML 1.1 rules or their own defaults, so check your parser's documentation and do not assume either version.

# Illustrative: how a YAML 1.1-style parser may read these
country: NO        # may become boolean false
version: 1.10      # becomes the number 1.1
file_mode: 0755    # may become octal 493

# Quoting keeps them as strings under any version
country: "NO"
version: "1.10"
file_mode: "0755"

The reliable fix is to quote any value that must stay a string, especially country codes, version numbers, IDs with leading zeros, and anything that looks like a boolean or a time. JSON does not have this problem, because every string is quoted.

Will the output remain readable and usable where you need it?

Copy and paste: YAML depends on exact indentation, so it is fragile when it passes through tools that reflow or retype text. Rich-text editors, chat apps, email clients and word processors can convert spaces to tabs, collapse leading whitespace, insert non-breaking spaces, or replace straight quotes with curly quotes. Each of these can break YAML or quietly change its structure. JSON survives whitespace changes but fails on curly quotes, stray trailing commas, or truncated brackets. Behavior varies by application and has not been tested here. The safe habit is to parse the pasted text again at its destination and not assume it arrived intact. Code blocks, plain-text editors and file attachments are generally safer carriers than formatted message bodies.

Readability and accessibility: in YAML, nesting is carried by indentation alone. That is easy to scan visually but can be harder to follow when the indentation is not visible, for example when text is reflowed or read out without whitespace cues. JSON's explicit delimiters show structure as characters. This guide has no screen reader test data for either format. If accessibility matters for your audience, check with the assistive technology they actually use, and consider an editor that shows indentation guides or structure outlines.

Compatibility: valid JSON is interpreted consistently by most parsers. One known exception is very large integers. JavaScript numbers are double-precision floats and cannot represent integers above 2^53 exactly, so IDs this large are often sent as strings. Duplicate keys are another area where libraries differ. YAML compatibility depends on which spec version and schema the parser implements, as shown above. Before relying on a file in a new system, confirm which parser that system uses.

Safe parsing: some YAML libraries can construct arbitrary language objects from tagged input when you use their full or unsafe loading functions. With untrusted input, that can lead to code execution. Use the library's safe loading mode for any YAML you did not write. Aliases also allow a small document to expand into a very large structure, so services that accept YAML from users should set size or depth limits. JSON parsers do not construct objects from type tags, but limits on input size are still sensible.

Sensitive input and online converters: configuration files often contain API keys, database passwords, internal hostnames and tokens. Pasting them into a web-based converter or validator sends that content to a third party, where it may be logged or retained. Prefer local tools for anything sensitive, or remove secrets and replace them with placeholders before using an external service.

# Illustrative local checks (not run for this guide)

# Validate and pretty-print JSON with Python's standard library
python3 -m json.tool config.json

# Convert YAML to JSON using PyYAML's safe loader (requires PyYAML)
python3 -c 'import sys, json, yaml; print(json.dumps(yaml.safe_load(sys.stdin), indent=2))' < config.yaml

Gaps in this comparison

This guide does not include parsing speed benchmarks, file size measurements, or observed output from specific converters or editors. No verified data for those was available. If performance or exact output formatting matters for your choice, test the libraries and tools you plan to use with representative files.