YAML to JSON: Why Developers Transition Formats

MT
Written by the MyToolDock team
Category: Developer Tools · Published

In this guide

YAML and JSON describe the same kinds of data, but they suit different readers. YAML is friendly to people and common in configuration files; JSON is strict and universal for APIs. Converting between them is routine, and a few differences cause most of the surprises.

How they differ

YAML uses indentation instead of braces, allows comments, and can write many values without quotes. JSON requires double-quoted keys and strings, has no comments, and uses explicit braces and brackets. Every JSON document is nearly valid YAML, but YAML has features JSON lacks, such as comments and anchors.

Indentation errors

YAML is whitespace-sensitive. Use spaces, never tabs, and keep indentation consistent. One misaligned line can move a key into the wrong parent without any error. When converting, check the resulting JSON structure to confirm values ended up where you intended.

Type surprises

Unquoted YAML values are interpreted. The word no or off may become a boolean false in some parsers, a value like 1.10 becomes the number 1.1, and a date such as 2024-01-05 may become a date object. Quote values when you need them kept as text, for example version numbers and country codes.

What is lost in conversion

Converting YAML to JSON drops comments, since JSON has nowhere to keep them, and expands anchors and aliases into repeated data. Converting back will not restore them, so keep the original YAML.

Validation first

Validate the YAML before converting. A parser error with a line number saves time. For configuration that drives deployments, review the converted output carefully before use.

Worked example: a small config

The YAML name: MyToolDock, a tags list of pdf and seo, and active: true went through the YAML to JSON converter and came out as a JSON object with name as a string, tags as an array of two strings and active as the boolean true. YAML's indentation and dashes became braces, brackets and commas.

Types are inferred, so true became a boolean and not the text "true". If you need a value to stay a string, quote it in the YAML first, and validate the YAML before converting so that a typo is caught early.

Key Takeaways

Frequently Asked Questions

Is JSON valid YAML?

Almost always, yes. YAML 1.2 was designed to include JSON.

Why did my yes become true?

Some YAML parsers treat unquoted yes and no as booleans. Quote the value to keep it as text.

Can I convert back without losing comments?

No. Keep the original YAML file if comments matter.

Free tools mentioned in this guide

Browse every Developer Tools utility, or see all tools.

Recommended Reading

Developer Scratchpad

Copied to clipboard!