How to Convert YAML to JSON (and Back)
YAML and JSON describe the same data model, so conversion is lossless in almost every case. Here's how to do it from the command line, in code, or in the browser.
Command line: yq
yq is the quickest way if you're already in a terminal:
# YAML → JSON
yq -o=json config.yaml
# JSON → YAML
yq -P config.json
Python
PyYAML reads the YAML; the built-in json module writes it out:
import yaml, json
with open("config.yaml") as f:
data = yaml.safe_load(f)
print(json.dumps(data, indent=2))
Use safe_load, not load — plain load can execute arbitrary Python objects embedded in untrusted YAML.
JavaScript
With the js-yaml package:
import fs from "node:fs";
import yaml from "js-yaml";
const data = yaml.load(fs.readFileSync("config.yaml", "utf8"));
fs.writeFileSync("config.json", JSON.stringify(data, null, 2));
Going the other way is yaml.dump(JSON.parse(...)).
What gets lost in translation
Data converts cleanly; presentation doesn't. Watch for these:
- Comments are dropped. JSON has no comment syntax, so
# notesin your YAML vanish. Converting back won't restore them. - Anchors get expanded. YAML
&anchor/*aliasreferences become duplicated values in JSON — see YAML anchors and aliases. - Unquoted scalars can surprise you. In YAML 1.1,
noparses asfalseand3.10as a number. Quote anything that must stay a string. - Keys must be strings. YAML allows non-string mapping keys; JSON doesn't, so converters coerce them.
If the output looks wrong, the YAML itself may be the problem — how to fix YAML errors covers the usual suspects.
Convert without installing anything
For a one-off file, skip the tooling: paste your YAML into the free JSON/YAML converter, and it validates the input and converts in either direction (TOML too). Errors are flagged with line numbers, which makes it a handy YAML linter even when you don't need the conversion.
Still choosing a format for your project? See JSON vs YAML vs TOML.
Got a config file to check?
Open the config toolkit →