Guide
How to convert YAML to JSON without surprises
Identify the compatible subset, preserve types, and detect comments, anchors, tags, or keys that JSON cannot represent.
by Tools in a Tab · Published on · Reviewed on
Short answer
Converting YAML to JSON is not merely adding braces. You first resolve YAML values and then verify that the resulting structure belongs to JSON’s data model.
A subset that converts cleanly
service: api
replicas: 3
enabled: true
ports:
- 8080
- 8443
becomes:
{
"service": "api",
"replicas": 3,
"enabled": true,
"ports": [8080, 8443]
}
Mappings with string keys, sequences, and scalars equivalent to strings,
numbers, booleans, or null have a natural translation.
Features to inspect first
- Comments: JSON cannot retain them as comments.
- Anchors and aliases: they express references in the YAML graph.
- Tags: they can construct values outside the JSON type set.
- Complex keys: JSON object names must be strings.
- Multiple documents: one JSON document does not directly represent a YAML stream.
- Non-finite values:
NaNand infinities are not JSON numbers.
The YAML to JSON converter deliberately accepts one JSON-representable YAML 1.2 Core document and rejects features that would make the result ambiguous. Rejection is safer than silently discarding meaning.
Scalars that look like other types
Parser version and schema determine how unquoted scalars resolve. YAML 1.2 removed several problematic YAML 1.1 implicit conversions, but older systems may behave differently. Quote a string when its numeric or boolean appearance must not change its type.
Procedure
- Identify the YAML version and features used by the source.
- Replace references or tags with explicit data if the consumer needs them.
- Convert under size and depth limits.
- Validate the resulting JSON.
- Compare important types and values, not only visual layout.
The YAML 1.2.2 specification separates the representation graph, serialization tree, and presentation stream. JSON conversion operates on resolved data, not comments or styling.