YAML zu JSON
Konvertieren Sie YAML-Dokumente in JSON-Format unter Beibehaltung der Struktur
Converting YAML to JSON: Navigating Feature Loss
YAML (YAML Ain't Markup Language) is a data serialization language designed for human readability and configuration authoring. Its superset relationship with JSON means every valid JSON document is also valid YAML, but the reverse is not true β YAML offers features that have no direct representation in JSON. When converting YAML to JSON, these YAML-specific constructs must be resolved, flattened, or discarded, resulting in a structurally equivalent but semantically reduced output. Understanding what survives the conversion and what does not is essential for developers migrating configuration between ecosystems.
YAML Features That Do Not Survive Conversion to JSON
YAML 1.2 defines several constructs that JSON cannot represent. When converting YAML to JSON, these features are either resolved into their expanded form or lost entirely:
- Comments: YAML supports inline (
# comment) and block comments. JSON has no comment syntax whatsoever β all comments are stripped during conversion with no way to preserve them in the output. This is the most commonly cited limitation for configuration files that rely on inline documentation. - Anchors and Aliases: YAML's
&anchorand*aliasmechanism allows a single value to be defined once and referenced multiple times. During conversion, aliases are dereferenced β every reference is replaced with a full copy of the anchored value. The resulting JSON is larger and loses the DRY (Don't Repeat Yourself) semantics. - Multi-document streams: A single YAML file can contain multiple documents
separated by
---. JSON has no multi-document concept, so each document must be converted independently or wrapped in a JSON array. - Complex mapping keys: YAML allows sequences or mappings as keys
(e.g.,
[host, port]: value). JSON requires all object keys to be strings, so complex keys must be serialized or rejected. - Sets and ordered maps: YAML defines
!!setand!!omaptypes. JSON has no native set or ordered-map construct β sets become arrays, and ordered maps become regular objects where key order is not guaranteed by the spec. - Custom tags: YAML's tag system (
!tag,!!type) enables application-specific type information. JSON provides no tagging mechanism, so type metadata is lost.
The practical impact is that YAML-to-JSON conversion is a lossy operation for documents that use these features. Round-tripping (YAML β JSON β YAML) will not reproduce the original document if it contained comments, anchors, multi-document separators, or custom tags.
Schema Mapping Challenges: YAML Types to JSON Primitives
YAML 1.2 defines three schemas β Failsafe, JSON, and Core β each with different type resolution
rules. The Core schema (the default for most parsers) recognizes boolean values like
yes, no, on, off, true,
false and converts them to JSON booleans. This can produce unexpected results when
values intended as strings (like a country code NO for Norway) are silently converted
to false.
Other type-mapping challenges include:
- Null representations: YAML accepts
~,null,Null,NULL, and empty values as null. JSON only accepts lowercasenull. - Integers with alternate bases: YAML supports octal (
0o755), hexadecimal (0xFF), and binary literals. JSON only supports decimal notation, so these are converted to their decimal equivalents. - Infinity and NaN: YAML represents these as
.inf,-.inf, and.nan. JSON has no representation for non-finite numbers β converters typically emitnullor raise an error. - Timestamps: YAML natively recognizes date and datetime formats
(e.g.,
2024-01-15becomes a date object). JSON treats these as plain strings unless the application layer interprets them. - Binary data: YAML's
!!binarytag encodes binary content as Base64. In JSON, this becomes a plain string β the binary semantics are lost without the tag.
Developers should explicitly quote YAML values that might trigger unwanted type coercion, especially when the output JSON will be consumed by strict parsers. Using YAML's JSON schema (which disables implicit type resolution) can reduce surprises during conversion.
When and Why to Convert YAML to JSON
Despite the feature loss, YAML-to-JSON conversion is a frequent operation in modern development workflows. Common scenarios include:
- API consumption: REST APIs almost universally accept JSON. Kubernetes manifests, Docker Compose files, and Ansible playbooks are authored in YAML but often need to be submitted to JSON-only endpoints for validation or processing.
- Tooling compatibility: Many linters, validators, and code generation tools (like OpenAPI generators) accept JSON but not YAML. Converting once for tool consumption avoids maintaining parallel files.
- Language ecosystems: While Python and Ruby have excellent YAML libraries,
ecosystems like browsers, Deno, and many serverless runtimes ship with native JSON parsing
(
JSON.parse()) but require third-party dependencies for YAML. - Configuration compilation: CI/CD pipelines often compile human-authored YAML configurations into machine-consumable JSON before deployment, allowing developers to write in YAML's clean syntax while deploying JSON for performance.
- Debugging and inspection: JSON's ubiquitous tooling (formatters, diff tools, path queries with JSONPath or jq) makes it useful to convert YAML temporarily for analysis.
The key distinction from JSON-to-YAML conversion is directionality of information loss. Converting JSON to YAML is lossless β you gain readability without losing data. Converting YAML to JSON is potentially lossy β you gain compatibility but may lose comments, anchors, and type metadata that informed the original document's structure.
Handling Anchor Resolution During Conversion
YAML anchors (&) and aliases (*) are one of the language's most
powerful features for reducing repetition in large configuration files. During conversion to JSON,
every alias is expanded in place β the anchor definition is inlined wherever it is referenced.
This means a 50-line YAML file with extensive anchor reuse might expand to a 500-line JSON file
with fully duplicated structures.
Merge keys (<<:) compound this issue. A merge key combines multiple anchor
references into a single mapping, enabling inheritance-like patterns common in Docker Compose
and CI configuration. After JSON conversion, the merged result is a flat object with all inherited
properties explicitly listed β there is no indication that values originated from shared definitions.
For large configurations that rely heavily on anchors, developers should consider whether the
expanded JSON is maintainable or whether a different approach (like JSON references via
$ref) is needed to preserve the DRY intent in the target format.
Code Examples
YAML features lost during conversion to JSON
# YAML input with features that don't survive conversion
# This comment will be lost in JSON
defaults: &defaults # Anchor definition
adapter: postgres
host: localhost
port: 5432
development:
<<: *defaults # Merge key + alias
database: app_dev
production:
<<: *defaults # Same anchor reused
database: app_prod
host: db.example.com
--- # Multi-document separator (no JSON equivalent)
# Second document
metrics:
enabled: yes # Becomes boolean true in JSON
endpoint: ~ # Becomes null in JSON
timeout: 0x1E # Hex 30 β decimal 30 in JSONOutput:
// Resulting JSON (from first document only):
{
"defaults": {
"adapter": "postgres",
"host": "localhost",
"port": 5432
},
"development": {
"adapter": "postgres",
"host": "localhost",
"port": 5432,
"database": "app_dev"
},
"production": {
"adapter": "postgres",
"host": "db.example.com",
"port": 5432,
"database": "app_prod"
}
}
// Comments lost, anchors dereferenced, merge keys expanded,
// second document discarded, hex converted to decimalStandards & Specifications
- YAML 1.2 Specification β Complete YAML 1.2.2 language specification defining anchors, aliases, tags, multi-document streams, and schema resolution rules
- ECMA-404 (JSON) β The JSON data interchange format β defines the limited type system that YAML values are mapped into during conversion