How to Convert JSON to YAML (and YAML to JSON)

07 Oct 2026 1,528 words

How to Convert JSON to YAML (and YAML to JSON)

JSON and YAML are the two most common formats for structured data in modern software. APIs speak JSON, Kubernetes manifests and CI pipelines speak YAML, and at some point almost every developer needs to move data between the two. Converting JSON to YAML looks trivial until a schema key collides with a YAML boolean, a multi-line string loses its formatting, or an empty object turns into the wrong value entirely.

This guide explains the conversion rules in both directions, the mistakes that silently corrupt data, and the practical workflows that keep your files valid. When you want to transform a real payload without writing a one-off script, you can paste it into the JSON to YAML Converter tool and get the result instantly.

Why JSON and YAML Coexist

Both formats represent the same abstract structures: key-value maps, ordered lists, scalars, and nested combinations of them. The difference is philosophy.

JSON was designed as a compact, unambiguous data-interchange format for machines. Every string must be quoted, every member separated by commas, and comments are not allowed. Its strictness is a feature: parsers never have to guess.

YAML was designed to be pleasant for humans to write and read. Indentation replaces braces, keys do not need quotes, and comments are welcome. The trade-off is a much larger specification with surprising edge cases — which is exactly where naive conversions break.

Typical Conversion Scenarios

  • Kubernetes and CI/CD: you generate a manifest or pipeline definition as JSON (from an API or template) and must hand it over as YAML for a deployment.yaml file.
  • API testing: an API returns JSON, but your configuration system ingests YAML.
  • Configuration migrations: moving application settings from config.json to config.yaml (or the reverse) during a refactor.
  • Documentation: JSON samples embedded in docs read better as annotated YAML.

JSON to YAML: The Conversion Rules

At its core, the mapping is mechanical:

JSON YAML
{ ... } object Mapping (key: value pairs, indented)
[ ... ] array Block list (- items) or flow sequence ([a, b])
"string" Bare scalar (quotes optional)
42, 3.14 42, 3.14
true, false true, false
null null or ~
{} {} (empty flow mapping)
[] [] (empty flow sequence)

A minimal example:

{
  "app": {
    "name": "help2code",
    "port": 8080,
    "debug": true
  },
  "features": ["formatter", "converter"]
}

Becomes:

app:
  name: help2code
  port: 8080
  debug: true
features:
  - formatter
  - converter

Rule 1: Indentation Is Structure

YAML has no commas or braces, so whitespace carries meaning. Use a consistent number of spaces (two is the common convention) and never tabs — most YAML parsers reject tabs outright. When converting deeply nested JSON, keep one indent level per JSON nesting level and your output will remain valid.

Rule 2: Quotes Are Optional — Until They Are Not

JSON requires quotes around every key and string. YAML allows bare words, but you must keep (or add) quotes when a value would otherwise be misread:

  • Strings that look like numbers: "8080", "1e5"
  • Strings that look like booleans: "yes", "no", "on", "off"
  • Strings that look like null: "null", "~"
  • Strings containing : (colon followed by space), leading *, &, !, or other indicator characters
  • Strings starting or ending with spaces

A safe converter quotes anything ambiguous; a careless one strips all quotes and changes your data types.

Rule 3: Empty Values Need Special Care

JSON distinguishes null and {}. In YAML, a key with no value parses as null:

settings:    # this is null, not an empty object

An empty object must be written as {}. The same applies to arrays: an empty JSON array [] must stay [], not disappear into a blank line.

Rule 4: Multi-Line Strings

JSON escapes newlines inside a single-line string ("line1\nline2"). YAML offers block scalars that preserve real line breaks:

script: |
  echo hello
  echo world

The | literal block keeps newlines; the folded style > joins them into paragraphs. When converting, choose the block style for anything longer than a sentence — it is the main readability win of YAML.

YAML to JSON: Converting Back

The reverse direction is stricter, because JSON cannot express everything YAML can:

  • Comments are dropped. YAML comments have no JSON equivalent, so they are lost during conversion. Keep important notes outside the data or in a _comment key if you must preserve them.
  • Every string must be quoted in the output, and every member needs a comma.
  • Anchors and aliases (&/*) must be expanded. JSON has no reference mechanism, so a YAML file using anchors must be fully dereferenced first.
  • Multiple documents are flattened. YAML allows ----separated document streams; JSON must be a single value (an array of documents is a common compromise).
  • Tagged scalars (!!str, !!int, custom tags) must be resolved to plain values.

The Yes/No Trap

This is the single most common bug in YAML-to-JSON conversion, especially with files written on Windows or by hand. In YAML 1.1 (which many parsers, including PyYAML, still follow), yes, no, on, and off are booleans — not strings. So this YAML:

enabled: yes

converts to "enabled": true in JSON, not "enabled": "yes". If your application expects the literal string, your config has just been corrupted. Quote the value ("yes") or fix it at the source.

Other surprising coercions include 0123 becoming octal, 1_000 becoming an integer, and sexagesimal values like 1:30 being interpreted as time. When in doubt, quote scalars in YAML — the safest conversion is the one with no surprises.

Validating the Result

Never ship converted output without validating both sides:

  1. Parse the source before converting. If the JSON is invalid, no converter can fix it — repair it first with the JSON Formatter, which pretty-prints and points out the exact syntax error.
  2. Parse the target after converting. A YAML linter catches indentation and duplicate-key errors that visual inspection misses; the YAML Formatter reformats and flags problems in one step.
  3. Round-trip check for critical data. Convert JSON → YAML → JSON and diff against the original. If the round-trip is not identical, the converter (or the source file) dropped or altered something.

Round-Trip Example

original.json  --convert-->  config.yaml  --convert-->  result.json
      \__________________________________________________/
                  diff should be empty (modulo key order)

Key order is not semantically meaningful in either format, so compare parsed structures rather than raw text when diffing.

Tools vs Scripts: When to Use Which

A quick one-liner is fine when you are already at the terminal:

# JSON to YAML with yq
yq -P '.' data.json > data.yaml

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

For occasional conversions, an in-browser tool is faster: no shell setup, no dependency to install, and you can inspect the output visually before copying it. The JSON to YAML Converter handles both directions, including validation, which makes it a good fit for API payloads, Kubernetes manifests, and CI configuration you touch once a week rather than once an hour.

Scripts win when conversion is part of an automated pipeline — build steps, config generation, or data migration jobs — where it must run unattended and repeatable.

Frequently Asked Questions

Is YAML 100% compatible with JSON? Yes in one direction: every valid JSON document is also valid YAML (JSON is a subset of YAML 1.2). The reverse is not true — YAML features like comments, anchors, and multiple documents have no JSON representation.

Which format should I choose for new configuration? Pick JSON when the file is machine-generated, validated by a strict schema, or consumed by systems without a YAML library. Pick YAML when humans edit the file regularly — the comments and lighter syntax pay for themselves. For very large config surfaces, many teams use YAML at the top level and embed JSON where precision matters.

Why did my numbers turn into strings after conversion? Because the source was quoted. In JSON, "8080" is a string; if you keep the quotes in YAML it stays a string. Remove the quotes (and confirm the value is not ambiguous) to convert it to a number.

Does converting change data types? Only if the source format uses different scalar rules — the yes/no case described above is the classic example. Use explicit quoting on both sides and types survive conversion intact.

Conclusion

Converting JSON to YAML and back is a solved problem mechanically, but correctness depends on the details: indentation, quoting, empty values, and YAML's liberal scalar interpretation. Validate both directions, run a round-trip diff for anything critical, and keep a converter you trust within reach. For everyday payloads, the JSON to YAML Converter on Help2Code performs the transformation and validation in one step, while the surrounding guides — Convert JSON to CSV and JSON Schema Basics — cover the neighboring formats you are likely to meet next.


About this article

Learn how to convert JSON to YAML and back again, when each format shines, and how to avoid the most common conversion mistakes.


Related Articles


Related Tools