Last updated
YAML vs JSON
YAML (YAML Ain't Markup Language) and JSON (JavaScript Object Notation) represent the same data structures but with different syntax. YAML is designed for human readability — it uses indentation instead of braces, allows comments, and supports multi-line strings natively. JSON is designed for machine parsing — it's strict, unambiguous, and universally supported.
Syntax Comparison
| Feature | YAML | JSON |
|---|---|---|
| Comments | # comment | Not supported |
| Strings | Unquoted or quoted | Must be double-quoted |
| Null | null or ~ | null |
| Booleans | true, yes, on | true, false only |
| Multi-line strings | | (literal) or > (folded) | Escape
|
| Trailing commas | N/A | Not allowed |
YAML to JSON Conversion
// Using js-yaml library
import yaml from 'js-yaml';
function yamlToJson(yamlString, pretty = true) {
try {
const parsed = yaml.load(yamlString);
return JSON.stringify(parsed, null, pretty ? 2 : 0);
} catch (e) {
throw new Error(`YAML parse error: ${e.message}`);
}
}
// Example
const yamlInput = `
name: John Doe
age: 30
address:
street: 123 Main St
city: Springfield
hobbies:
- reading
- coding
`;
console.log(yamlToJson(yamlInput));
// {
// "name": "John Doe",
// "age": 30,
// "address": { "street": "123 Main St", "city": "Springfield" },
// "hobbies": ["reading", "coding"]
// }
YAML Gotchas
- Norway problem:
NOis parsed as booleanfalsein YAML 1.1. Use quotes:"NO". - Octal numbers:
010is parsed as 8 (octal) in YAML 1.1. Use0o10in YAML 1.2. - Tabs: YAML does not allow tabs for indentation — only spaces.
- Duplicate keys: YAML allows duplicate keys; the last value wins (behavior is undefined).