GameParticles
Developer

YAML vs JSON: Syntax, Key Differences and When to Use Each

YAML vs JSON explained: indentation rules, comments, anchors and the Norway problem, with the same config in both formats and clear advice on when each wins.

Updated

YAML and JSON describe the same kind of data: nested maps, lists, strings, numbers, booleans and null. JSON marks structure with braces, brackets and quotes; YAML marks it with indentation and line breaks, and adds comments, anchors and multi-line strings. JSON is the safer choice for data exchanged between programs, while YAML is more comfortable for configuration that people write by hand.

The same config in both

In JSON:

{"name": "web", "replicas": 3, "ports": [80, 443], "env": {"DEBUG": false, "REGION": "eu-west-1"}}

In YAML, each item below is one line of the file. The lines marked as indented start with two spaces, which is what places them under the key above:

  • # Web service settings
  • name: web
  • replicas: 3
  • ports:
  • - 80 (indented two spaces)
  • - 443 (indented two spaces)
  • env:
  • DEBUG: false (indented two spaces)
  • REGION: eu-west-1 (indented two spaces)

The YAML has no braces, no quotes, and a comment on the first line. It also depends entirely on those leading spaces: remove them and DEBUG becomes a top-level key instead of part of env.

YAML syntax in brief

  • A map is written as key: value, one pair per line. The space after the colon is required.
  • Nesting is shown by indenting with spaces. Tabs are not allowed for indentation.
  • A list is a series of lines starting with - . The inline forms [a, b] and {a: 1} also work, and are in fact JSON syntax.
  • Strings usually need no quotes. Use quotes when the value could be mistaken for something else or contains characters such as : or #.
  • # starts a comment that runs to the end of the line.
  • A line containing only --- starts a new document, so one file can hold several.
  • After a key, a pipe character starts a block of text that keeps its line breaks, and > starts a block whose lines are folded into one paragraph. These make long scripts and messages readable without \n escapes.

Side by side

FeatureJSONYAML
StructureBraces and bracketsIndentation
CommentsNoYes, with #
String quotesAlways requiredUsually optional
Multi-line stringsEscaped with \nBlock scalars
Reuse of valuesNoAnchors and aliases
Multiple documents per fileNoYes, separated by ---
Type guessingNone, types are explicitUnquoted scalars are interpreted
Specification sizeVery smallLarge
Typical useAPIs, data exchange, lock filesConfig, CI pipelines, infrastructure

Comments

This is the difference people notice first. JSON has no comment syntax at all, so a config file cannot explain why a timeout is 30 seconds or temporarily disable a line. YAML comments make a file self-documenting, which is the main reason tools like Kubernetes and GitHub Actions chose it.

One consequence: comments are not data. Converting YAML to JSON discards them, and a program that loads and rewrites a YAML file often loses them as well.

Anchors and aliases

YAML lets you name a value and reuse it elsewhere in the same file. &name after a key sets an anchor on that key's value, and *name inserts the same value again. With defaults: &defaults {retries: 3, timeout: 30} defined once, a later staging: *defaults gives staging the same settings.

Many parsers also support the merge key, written <<: *defaults, which copies an anchored map into another map so individual keys can then be overridden. It is widely used in Docker Compose and CI files to avoid repeating blocks. The merge key came from YAML 1.1 and is not part of the 1.2 core, so support varies between tools.

JSON has nothing comparable. When YAML with anchors is converted, each alias is expanded into a full copy.

The Norway problem

YAML decides the type of an unquoted value by its appearance. Under YAML 1.1 the list of boolean spellings was long: yes, no, on, off, y, n and their capitalized forms, as well as true and false. So a list of country codes containing NO for Norway loads with false in that position. The same rule turns an answer of yes or a switch value of off into a boolean.

Related surprises come from the same guessing:

  • version: 1.10 is read as the number 1.1. Quote version numbers.
  • 22:22 can be read as a base-60 number under YAML 1.1, which is why Docker Compose documentation recommends quoting port mappings.

YAML 1.2, published in 2009, cut booleans down to true and false and dropped the base-60 format. But several widely used libraries, PyYAML among them, still apply 1.1 rules, so you cannot assume the fix is in effect. The reliable habit is to quote any string that could be read as something else: "NO", "1.10", "22:22".

In JSON a string is always in quotes, so it is never mistaken for a boolean or a number. YAML trades that certainty for less typing.

When each wins

Choose JSON when:

  • Programs are talking to programs: API requests and responses, message queues, log records.
  • The file is generated and consumed by tools, such as lock files and build output.
  • You want identical parsing everywhere. JSON's grammar is small enough that implementations rarely disagree.
  • Input is untrusted. Some YAML loaders can construct arbitrary objects from tags, which is why libraries offer a separate safe loading mode.

Choose YAML when:

  • People write and review the file, and comments would help.
  • The tool you are configuring expects it: Kubernetes, Docker Compose, GitHub Actions, GitLab CI, Ansible, OpenAPI specs.
  • The file holds long text blocks such as shell scripts.

A block indented one level too far is still valid YAML with a different meaning. Converting to JSON makes the real structure explicit, which is a quick way to check what a parser actually sees.

Converting between them

The YAML to JSON Converter works in both directions. It handles the everyday shapes of config files: nested maps, lists, lists of maps, quoted and unquoted scalars, numbers, booleans and null. Comment lines are skipped, since JSON has nowhere to put them. It treats lowercase yes and no as booleans in the YAML 1.1 style, so quote those values if you mean the words. For files that rely on anchors, merge keys or several documents, check the result against the parser your own tool uses.

Going from JSON to YAML, it writes two-space indentation and adds quotes where a string contains characters such as : or # that would otherwise change its meaning. If the JSON side will not parse, the JSON Formatter shows the error; what a JSON file is covers the syntax rules.

Try it

Paste a Compose file, a workflow or any config into the YAML to JSON Converter and read the JSON output to see exactly how the indentation was understood. Switch direction to turn an API response into YAML you can drop into a config file.

Tools in this guide

Frequently asked questions

What is YAML?

YAML is a text format for structured data that uses indentation instead of brackets. The name stands for YAML Ain't Markup Language. It is used mainly for configuration files, including Docker Compose, Kubernetes manifests, GitHub Actions workflows and Ansible playbooks.

Is YAML a superset of JSON?

In practice, yes. YAML 1.2 was designed so that valid JSON is also valid YAML, which means a YAML 1.2 parser can read a JSON file. The reverse is not true: JSON parsers cannot read YAML's indentation, comments or anchors.

Can you use tabs in YAML?

Not for indentation. YAML requires spaces, and a tab at the start of a line is a syntax error. Any consistent number of spaces works, but two per level is the common convention. Tabs are allowed inside quoted string values.

What is the Norway problem in YAML?

Under YAML 1.1 rules the unquoted values yes, no, on and off are booleans, so the country code NO for Norway is read as false. YAML 1.2 removed this, but many parsers still follow 1.1. Quoting the value as "NO" avoids it.

More developer guides

JSON Formatter
Developer · Format, validate and minify JSON with syntax highlighting.
↵
Base64 Encode / Decode
Developer · Encode text to Base64 or decode Base64 back to plain text.
↵
URL Encoder / Decoder
Developer · Encode or decode URL components and query strings.
↵
Hash Generator
Developer · Generate MD5, SHA-1, SHA-256 and SHA-512 hashes.
↵
UUID Generator
Developer · Generate UUIDs v4 (random) in bulk with one click.
↵
Regex Tester
Developer · Test regular expressions against text with live match highlighting.
↵
Word Counter
Text · Count words, characters, sentences, paragraphs and reading time.
↵
Case Converter
Text · Convert text between UPPER, lower, Title, camelCase, snake_case and more.
↵
List Sorter
Text · Sort, reverse, deduplicate and shuffle lists of text.
↵
Markdown Preview
Text · Write Markdown and see a live rendered preview side by side.
↵
Percentage Calculator
Numbers · Calculate percentages, increases, decreases and what % one number is of another.
↵
Color Converter
Colors · Convert colors between HEX, RGB, HSL and HSV instantly.
↵
Snake
Arcade · Eat food, grow longer, don't hit the walls. A timeless classic.
↵
2048
Puzzle · Slide tiles and combine them to reach the legendary 2048 tile.
↵
Word Grid
Puzzle · Guess the hidden five letter word in six tries using color clues.
↵
Sudoku
Puzzle · Fill the 9x9 grid with logic. Four difficulties from easy to expert.
↵
Minesweeper
Strategy · Use number clues to clear the minefield. Classic logic, three levels.
↵
Breakout
Arcade · Smash every brick with paddle and ball. Power-ups, combos, endless levels.
↵
Typing Practice
Casual · Build your WPM and accuracy with timed drills from 30 seconds to 5 minutes. Find your weak keys.
↵
TypeRunner
Arcade · Multiplayer typing race. Race friends by link, beat computer runners, or chase your own ghost.
↵
Typing Blocks
Arcade · Type each word before its wooden block lands. Miss, and the pile climbs toward the line.
↵
Bubble Shooter
Arcade · Aim, bank shots off the walls, and pop groups of three or more bubbles.
↵
Road Rush
Arcade · Race seven rivals through traffic and punch your way to the front.
↵