Convert YAML to JSON
What a YAML to JSON converter keeps, changes and silently drops, plus how to check the output before you rely on it or share it.
Converting YAML to JSON is usually simple. Both formats describe the same kinds of data: mappings, lists, strings, numbers, booleans and null. The risk is in the details. Some YAML features have no JSON equivalent, and some YAML values are read as a different type than the author intended. This review explains what a conversion changes, where it can go wrong, and how to judge whether the output is fit for your purpose.
Is converting YAML to JSON right for your use?
Convert when a program, API or tool needs JSON and you want the same data in a stricter, widely supported form. JSON parsers exist in almost every language, and JSON's small grammar leaves little room for interpretation. The decisive tradeoff is that JSON is a lossy target for anything that is not data. Comments, anchors and document structure are discarded, and a few YAML values may change type before they ever reach the JSON writer.
Keep YAML as the source of truth when people edit the file by hand, when comments explain settings, or when you rely on anchors to avoid repetition. In those cases, generate JSON as a build or deployment step and leave the YAML file unchanged.
What the conversion actually changes
Converters can look like reverse, mirror or font tools, but they work differently. A YAML to JSON converter does not reorder characters, flip glyphs or substitute look-alike Unicode letters. It parses the YAML into a data structure and then writes that structure out as JSON. Text inside string values is stored unchanged. Only the surrounding syntax is replaced: indentation becomes braces and brackets, and unquoted keys and strings gain double quotes.
The meaning is set during parsing, not writing. If the parser reads a value as a boolean, the JSON will contain a boolean, even if the author meant a word. The table below lists the YAML features most likely to change or disappear.
| YAML feature | What happens in JSON |
| Comments (# ...) | Dropped; JSON has no comment syntax |
| Anchors and aliases (&name, *name) | Expanded into full copies; the reuse is lost |
| Merge keys (<<) | Resolved by parsers that support them; otherwise they may become a literal key or cause an error |
| Multiple documents separated by --- | A single JSON value cannot hold them; tools either reject the input, keep only one document or wrap them in an array |
| Non-string keys (numbers, booleans, complex keys) | JSON keys must be strings, so keys are converted to strings or rejected |
| YAML 1.1 booleans (yes, no, on, off, y, n) | Become true or false under YAML 1.1 parsers; remain strings under the YAML 1.2 core schema |
| Unquoted numbers with trailing or leading zeros (1.10, 0755) | 1.10 becomes the number 1.1; 0755 may be read as octal or decimal depending on the YAML version |
| Timestamps | May become date objects that the JSON writer cannot handle, or plain strings, depending on the library |
| .inf, -.inf, .nan | No standard JSON representation; output is either non-standard or an error |
| Duplicate keys | Invalid YAML, but some parsers silently keep the last value |
| Literal (|) and folded (>) block scalars | Become ordinary strings with newlines resolved; the block style itself is not kept |
| Custom tags (!!binary, application tags) | Converted, rejected or dropped depending on the library |
A worked example
The input below contains several values that commonly cause surprises.
# service config
name: api
version: 1.10
country: NO
port: "8080"
defaults: &base
retries: 3
primary:
<<: *base
timeout: 30
A YAML 1.1 parser such as Python's PyYAML, followed by an indented JSON dump, should produce the output below. This output was derived from the documented parsing rules; it is not a recorded test run.
{
"name": "api",
"version": 1.1,
"country": false,
"port": "8080",
"defaults": {
"retries": 3
},
"primary": {
"retries": 3,
"timeout": 30
}
}
Four things changed. The comment is gone. The version 1.10 became the number 1.1, which is a real problem if it was a version label. The country code NO became false. The merge key copied retries into primary, and the link to defaults no longer exists. The port survived as a string only because it was quoted. A YAML 1.2 parser would keep NO as the string "NO" but would still turn 1.10 into a number. The reliable fix is to quote values in the YAML that must stay strings.
Converting locally with a short script
A local script avoids sending data to a third party and makes each choice explicit. The Python example below uses PyYAML and the standard json module.
import json
import sys
import yaml
with open(sys.argv[1], encoding="utf-8") as f:
docs = list(yaml.safe_load_all(f))
data = docs[0] if len(docs) == 1 else docs
print(json.dumps(data, indent=2, ensure_ascii=False, allow_nan=False, default=str))
- safe_load_all reads every document in a multi-document file; safe_load raises an error when more than one document is present.
- Use the safe loaders. The unrestricted loader can build arbitrary Python objects from tagged input, which is unsafe for untrusted files.
- ensure_ascii=False writes non-ASCII characters as they are. The default escapes them, so an emoji becomes a pair of \u escape sequences and accented text becomes harder to read, although the decoded value is identical.
- allow_nan=False makes the script fail on infinity or NaN instead of emitting the non-standard tokens Infinity and NaN that strict JSON parsers reject.
- default=str turns dates and other unsupported objects into strings instead of raising a TypeError. Remove it if you would rather have the conversion fail loudly.
- PyYAML follows YAML 1.1, so the boolean and octal rules from the table apply. Libraries that implement YAML 1.2 behave differently on those values.
Will the JSON stay readable and usable after copying or sharing?
JSON is plain text, so it survives copy and paste better than styled or Unicode-substituted text. Characters are not swapped for look-alikes. Search and find-and-replace behave normally, and reading order is unchanged. Strings in right-to-left scripts are stored exactly as in the YAML. How they display depends on the editor or viewer, not on the conversion.
Problems arise when JSON passes through tools built for prose. Word processors, some chat apps and some email clients can replace straight quotes with curly quotes or insert non-breaking spaces. Either change makes the JSON invalid. Share JSON as a file or in a code block, and validate it after it arrives.
For people reading the data, JSON is denser than YAML. It uses heavy punctuation and has no comments, which makes long files harder to scan or review by ear. Pretty-printing with consistent indentation helps. When someone needs to understand the configuration, give them the original YAML or a short plain-language summary instead of the JSON. No assistive technology was tested for this review, so no claims are made about how any specific screen reader announces JSON.
Online converters and sensitive data
Configuration files often contain credentials, internal hostnames or tokens. A converter's appearance or marketing tells you nothing reliable about whether it processes input in the browser or on a server, or whether it keeps what you paste. Unless the tool's documented behavior settles that question, strip secrets before pasting or convert locally.
When to keep plain YAML instead
- The file is maintained by people and its comments carry meaning.
- Anchors and merge keys keep a large configuration manageable.
- The consuming tool already accepts YAML.
- The file holds several documents that must stay separate.
- You need to preserve exact formatting for reviews or diffs.
Checklist before relying on the output
- Quote version numbers, country codes, ZIP codes, IDs with leading zeros and words such as yes, no, on and off whenever they must stay strings.
- Confirm which YAML version your parser implements.
- Check whether the input has multiple documents and decide how they should be represented.
- Validate the JSON with a strict parser, and with a schema if one exists.
- Compare a few key values between the YAML and the JSON, focusing on booleans, numbers and dates.
- Treat the YAML as the editable source and regenerate the JSON whenever it changes.
Gaps in this review
No specific converter product was examined, and no measurements, prices or test results were available. The behavior described comes from the YAML and JSON specifications and from the documented behavior of the Python libraries named above. Other converters may treat booleans, multiple documents, key order, large integers and custom tags differently. Check any particular tool against the cases in the table before trusting it with important data.