YAML to JSON and JSON to YAML

Summary
Definition: YAML and JSON model similar data but follow different constraints.
Why it matters: Conversions can lose meaning if unsupported features or types are used.
Pitfall: Plain scalars may resolve to unexpected types.
- YAML
- Human-friendly data format with multiple schemas.
- JSON
- Strict data format with a small fixed type set.
- Plain scalar
- Unquoted YAML value resolved by schema rules.
- JSON Schema
- YAML schema limited to JSON-compatible types.
- Type coercion
- Automatic conversion of plain scalars.
How YAML and JSON map
YAML 1.2 was designed to be compatible with JSON, but only a subset of YAML maps cleanly to JSON.
Only YAML data that conforms to the YAML JSON Schema can be converted to JSON safely.
What does not survive conversion
Some YAML features have no JSON equivalent and are discarded or flattened during conversion.
- Comments
- Anchors and aliases
- Custom tags
- Multiple documents
- Merge keys
Common mix-up: YAML 1.2 is a superset of JSON syntax, not a guarantee of round-trip safety.
Type conversion pitfalls
YAML resolves unquoted values using schema rules. Different parsers may apply YAML 1.1 or 1.2 behavior.
Implicit typing can change IDs, flags, or ports if values are not quoted.
Plain scalars may change type during conversion.
user:
id: "01"
active: yes
roles:
- admin
- editorValidate the output
Always validate the converted data to confirm structure and types.
- Convert YAML to JSON.
- Lint the JSON for validity.
- Convert back to YAML if needed.
- Review types for critical fields.
Tools and workflows
- Use YAML to JSON to inspect output.
- Use JSON to YAML for config generation.
- Validate with YAML Lint and JSON Lint.
Most conversion bugs come from assuming all YAML is JSON-compatible. Treat YAML as a superset with limits.