Basic JSON to YAML Conversion
Learn the fundamentals of converting JSON to YAML format. Understand how JSON objects, strings, and numbers map to their YAML equivalents with clear examples.
Detailed Explanation
Converting JSON to YAML is one of the most common tasks when working with configuration files. YAML (YAML Ain't Markup Language) is designed to be human-readable, and its syntax maps almost directly to JSON structures, making the conversion straightforward.
A simple JSON object:
{
"name": "devtoolbox",
"version": "1.0.0",
"private": true
}
Converts to this YAML:
name: devtoolbox
version: 1.0.0
private: true
Key differences in the conversion:
- Curly braces are removed. YAML uses indentation instead of
{}to define structure. - Quotes are optional. In YAML, strings that don't contain special characters don't need quotes. JSON requires double quotes around all keys and string values.
- Colons separate keys and values. Both formats use
:, but YAML requires a space after the colon. - No commas between entries. JSON uses commas to separate key-value pairs; YAML uses newlines.
Data types are preserved:
- JSON
"hello"(string) becomeshelloin YAML - JSON
42(number) stays42in YAML - JSON
true(boolean) staystruein YAML - JSON
nullstaysnullin YAML (or can be written as~)
The conversion is lossless: every valid JSON document has an exact YAML equivalent, and you can convert back to get the original data structure. This is because JSON is technically a subset of YAML (as of YAML 1.2).
Use Case
Converting a package.json or tsconfig.json file to YAML format when migrating a project's configuration to a tool that prefers YAML, such as moving from npm scripts to a YAML-based CI/CD pipeline.