YAML to JSON Conversion
Learn how to convert YAML documents to JSON format. Covers syntax mapping, common conversion pitfalls, and when to choose JSON over YAML for your project.
Basics
Detailed Explanation
Converting YAML to JSON is essential when an API or tool requires strict JSON input. While YAML is more readable for humans, JSON is the universal data interchange format supported by virtually every programming language and API.
A typical YAML document:
server:
host: localhost
port: 8080
debug: true
database:
url: postgres://localhost/mydb
pool_size: 5
Converts to this JSON:
{
"server": {
"host": "localhost",
"port": 8080,
"debug": true
},
"database": {
"url": "postgres://localhost/mydb",
"pool_size": 5
}
}
What changes during conversion:
- Indentation becomes braces and brackets. YAML's whitespace-based nesting is replaced with
{}for objects and[]for arrays. - All keys get quoted. JSON requires double quotes around every key.
- String values get quoted. Bare strings in YAML are wrapped in double quotes in JSON.
- Comments are lost. YAML supports
#comments, but JSON has no comment syntax. This is the most significant information loss during conversion.
Common pitfalls:
- YAML interprets unquoted
yes,no,on,offas booleans in YAML 1.1. If you meant these as strings, they becometrue/falsein JSON. - YAML numbers like
010may be interpreted as octal (value 8), not decimal 10. - Unquoted timestamps like
2024-01-15may be parsed as Date objects rather than strings.
Always validate the JSON output after conversion to ensure data types were preserved as intended.
Use Case
Converting a YAML configuration file to JSON before passing it as a payload to a REST API endpoint that only accepts JSON content type.