How to Convert YAML to JSON: Anchors, Multiline Strings, and the Norway Problem
Master YAML to JSON conversion: understand YAML 1.2 superset features, anchor references, multiline block scalars, and safe parsing in Node.js and Python.
YAML as a JSON Superset
YAML (YAML Ain't Markup Language) is a human-friendly data serialization language commonly used in DevOps, Kubernetes manifests, CI/CD pipelines (GitHub Actions, GitLab CI), and Docker Compose. Officially, YAML 1.2 is a superset of JSON: every valid JSON document is valid YAML, but YAML adds extensive features like indentation scoping, object anchors, multiline scalars, and implicit type conversion.
The Infamous "Norway Problem" in YAML
In YAML 1.1, country code abbreviations such as NO (Norway) or ON (Ontario) are automatically coerced to boolean false and true unless explicitly quoted in strings. When converted to JSON, this creates subtle bugs where country lists become ["US", "GB", false, "DE"].
# DANGEROUS in YAML 1.1:
countries:
- US
- NO # Naively parsed as boolean false!
# CORRECT:
countries:
- "US"
- "NO" # Explicit string quotes prevent boolean coercionAnchors (&) and Aliases (*): Resolving Object References
YAML allows developers to define reusable configuration blocks using anchors (&anchorName) and inject them elsewhere using aliases (*anchorName) or merge keys (<<: *anchorName). When converting YAML to JSON, these references must be fully dereferenced and cloned into independent JSON objects:
default_db: &db_config
host: localhost
port: 5432
pool: 10
production:
<<: *db_config
host: db.prod.cosharex.internal
pool: 50Multiline Strings: Literal (|) vs Folded (>)
| Symbol | Name | Behavior in JSON Output | Example Use Case |
|---|---|---|---|
| `|` | Literal Block | Preserves exact line breaks (`\n`) and whitespace | Shell scripts, private keys, ASCII art |
| `>` | Folded Block | Replaces newlines with single spaces (folds into a single paragraph) | Long descriptions, commit messages, documentation |
| `|-` / `>-` | Strip Chomping | Strips all trailing newlines at the end of the block | Single-line command strings |
| `|+` / `>+` | Keep Chomping | Preserves all trailing newlines at the end of the block | Formatted templates |
Converting YAML Safely in TypeScript & Python
import * as yaml from 'js-yaml';
export function yamlToJson(yamlContent: string): string {
// Use FAILSAFE_SCHEMA or JSON_SCHEMA to avoid unintended type coercion
const parsed = yaml.load(yamlContent, {
schema: yaml.JSON_SCHEMA
});
return JSON.stringify(parsed, null, 2);
}import yaml
import json
def convert_yaml_to_json(yaml_str: str) -> str:
# Always use safe_load to prevent arbitrary code execution vulnerabilities
data = yaml.safe_load(yaml_str)
return json.dumps(data, indent=2)Code Formatter & Converter Suite
Validate, format, minify, and convert JSON, SQL, YAML, XML, and code dialects directly on your local machine.
Frequently Asked Questions
Why is yaml.load() unsafe in Python?
In legacy PyYAML versions, `yaml.load()` allowed instantiation of arbitrary Python classes and system commands via custom tags (like `!!python/object/apply:os.system`). Always use `yaml.safe_load()` for untrusted user inputs.
Can JSON comments be preserved when converting to YAML?
Standard JSON does not support comments. However, tools parsing JSON with Comments (JSONC) can preserve inline comments as native YAML `#` comments during conversion.
Conclusion
Standard YAML parsers automatically convert values like `yes`, `no`, `true`, and `false` to booleans, and formats unquoted numbers to numeric types in your output JSON.
Related Articles
How to Validate JSON: Syntax Diagnostics, JSON Schema (Draft 2020-12), and Runtime Validation
Learn how to validate JSON data: debugging syntax errors, defining JSON Schema (Draft 2020-12) contracts, and validating runtime payloads with Ajv, Zod, and Pydantic.
Developer ToolsJSON vs XML: Structural Architecture, Parsing Performance, and Modern Use Cases
A deep architectural comparison between JSON and XML: data types, schema validation (JSON Schema vs XSD), payload overhead, and parsing performance.
ConvertersHow to Convert XML to JSON: Overcoming Attributes, Array Coercion, and Namespaces
Practical guide to transforming XML into clean JSON: handling attributes vs elements, array coercion traps, namespace stripping, and implementation recipes.