YAML to JSON (and Back): yq, Python and Node Commands
November 11, 2026 · 10 min read
YAML to JSON (and Back): Convert Configs Without Breaking Types
To convert YAML to JSON, parse the YAML into data and serialise that data as JSON. One command does it: yq -o=json config.yaml on the shell, yaml.safe_load plus json.dump in Python, or js-yaml in Node. The catch is that parsers disagree on values like NO, 1.10 and dates, so check those values after every conversion.
How YAML Maps onto JSON, Node by Node
Every YAML document is a tree of three node kinds, and each has a direct JSON counterpart. A mapping becomes an object, a sequence becomes an array, and a scalar becomes a string, number, boolean or null. Indentation carries the nesting in YAML, while JSON uses brackets and braces. Our YAML list syntax guide pairs each list form with the JSON array it produces.
Here's a small service config:
# App settings
name: billing-api
port: 8080
debug: false
owner: null
hosts:
- api.example.com
- api-eu.example.com
database:
engine: postgres
pool: 10
Converted with yq, it comes out as:
{
"name": "billing-api",
"port": 8080,
"debug": false,
"owner": null,
"hosts": [
"api.example.com",
"api-eu.example.com"
],
"database": {
"engine": "postgres",
"pool": 10
}
}
Numbers stay numbers, false stays a boolean and the comment disappears. Parsers also read JSON as YAML, because the YAML 1.2.2 spec says version 1.2's primary focus was making YAML a strict superset of JSON. Which format you should store configs in is a separate decision, and this guide doesn't try to settle it. Our YAML vs JSON comparison covers that choice.
Convert YAML to JSON on the Command Line with yq
yq by Mike Farah is a dependency-free Go binary that reads and writes YAML, JSON, XML, CSV and a few other formats. Its README covers direct downloads, package managers such as Homebrew (brew install yq) and Docker. We tested these commands with yq v4.54.
# Whole file, 2-space indent by default
yq -o=json config.yaml > config.json
# Compact, one line
yq -o=json -I=0 config.yaml
# Only one subtree, such as the services block of a Compose file
yq -o=json '.services' compose.yaml
The -o flag sets the output format and -I sets the indent. The quoted expression is a path, so .services returns just that mapping as a JSON object.
One naming trap: a different tool, kislyuk/yq, is a Python wrapper around jq that also installs a yq command. Its flags differ, so run yq --version before copying commands from a forum answer. We prefer the Go yq for this job because it's one binary with no Python or jq dependency.
How Do You Convert YAML to JSON in Python?
PyYAML is the usual choice. Install it with pip install pyyaml, then load with safe_load and write with the standard library's json module:
import json
import yaml
with open("config.yaml") as f:
data = yaml.safe_load(f)
with open("config.json", "w") as f:
json.dump(data, f, indent=2, default=str)
Two details matter. First, use safe_load, not yaml.load. The PyYAML documentation warns that yaml.load can build arbitrary Python objects, and PyYAML 6 raises a TypeError if you call it without a Loader argument.
Second, keep default=str. PyYAML turns an unquoted 2026-11-11 into a datetime.date, and json.dump can't serialise that. Without the fallback you get TypeError: Object of type date is not JSON serializable. With it, the date is written as the string "2026-11-11".
For a quick YAML to JSON conversion in a shell pipeline, the same logic fits on one line:
python3 -c 'import sys, json, yaml; json.dump(yaml.safe_load(sys.stdin), sys.stdout, indent=2, default=str)' < config.yaml
PyYAML implements YAML 1.1, which affects the type rules covered below. If you need YAML 1.2 behaviour in Python, ruamel.yaml follows 1.2 by default.
YAML to JSON in Node.js with js-yaml or yaml
In JavaScript, js-yaml and the yaml package both parse YAML into plain objects, and JSON.stringify does the rest:
const fs = require("fs");
const yaml = require("js-yaml");
const data = yaml.load(fs.readFileSync("config.yaml", "utf8"));
fs.writeFileSync("config.json", JSON.stringify(data, null, 2) + "\n");
With the yaml package the call is YAML.parse(text) instead. Both follow YAML 1.2 rules, and both throw an error on a duplicated key, which is safer than PyYAML's habit of silently keeping the last value.
Watch the major version. js-yaml 5.0, released in June 2026, changed the defaults. Version 4 turned 2026-11-11 into a JavaScript Date, which JSON.stringify prints as "2026-11-11T00:00:00.000Z". Version 5 leaves the date as the string "2026-11-11". It also stops expanding << merge keys unless you opt in with load(text, { schema: CORE_SCHEMA.withTags(mergeTag) }), per its migration guide.
JSON to YAML: Converting in the Other Direction
Going from JSON to YAML is the safer direction, because JSON's types are explicit. Every string arrives quoted, so the converter knows "NO" is text. The job is to keep it that way in the YAML it writes.
# yq: name the input and output formats
yq -p=json -o=yaml config.json > config.yaml
Spell out both flags. In our test, yq 4.54 printed a warning when we passed only -p=json, because its default output format now follows the file extension.
import json, yaml
with open("config.json") as f:
data = json.load(f)
print(yaml.safe_dump(data, sort_keys=False, allow_unicode=True))
PyYAML sorts keys alphabetically unless you pass sort_keys=False, and it escapes non-ASCII characters unless you pass allow_unicode=True. In Node, yaml.dump(data) from js-yaml or YAML.stringify(data) from yaml does the same job.
Here's where JSON to YAML converters differ. We fed each one "country": "NO", "enabled": "yes" and "version": "1.10":
| Converter | country | enabled | Safe for a YAML 1.1 reader? |
|---|---|---|---|
PyYAML safe_dump | 'NO' | 'yes' | Yes |
js-yaml 4 and 5 dump | 'NO' | 'yes' | Yes |
yq -o=yaml | NO | yes | No |
yaml stringify | NO | yes | No |
PyYAML, js-yaml and yaml all quote 1.10, since every parser would read it as a number. yq and yaml write YAML 1.2, where a plain NO is already a string, so their output is valid. A YAML 1.1 parser such as PyYAML reads it back as false, though. If a Python tool will consume the file, convert with PyYAML or js-yaml, or quote those values afterwards.
Why Did yes, no and 1.10 Change Type?
YAML guesses the type of every unquoted value, and the rules depend on the YAML version the parser implements. YAML 1.1's boolean type includes yes, no, on, off, y and n in several capitalisations. YAML 1.2's core schema accepts only true and false (in lower, title or upper case).
We ran the same file through each parser and printed the JSON. Results from PyYAML 6.0.3, js-yaml 5.5, yaml 2.9 and yq 4.54:
| YAML input | PyYAML (1.1) | js-yaml 5 / yaml (1.2) | yq |
|---|---|---|---|
country: NO | false | "NO" | "NO" |
enabled: yes | true | "yes" | "yes" |
version: 1.10 | 1.1 | 1.1 | 1.10 (a number) |
mode: 0755 | 493 (octal) | 755 | 755 |
release: 2026-11-11 | date object | "2026-11-11" | "2026-11-11" |
on: as a key | "true" | "on" | "on" |
That last row bites GitHub Actions users. A workflow's on: trigger key, loaded with PyYAML, becomes the boolean True, so the JSON key reads "true". GitHub's own parser handles it fine, but a PyYAML script won't.
Look closely at 1.10, too. yq keeps the literal text, but in JSON it's still an unquoted number, so any JSON reader turns it into 1.1.
Whatever the parser, the fix is to quote the value in the YAML source. version: "1.10" and country: "NO" come through every parser as strings. We prefer quoting any value that isn't obviously a number or boolean, because it makes the file mean the same thing to every tool. Our YAML format cheat sheet shows the quoting rules with examples.
What JSON Can't Keep: Comments, Anchors and Multiple Documents
JSON's data model, defined in RFC 8259, has no comments, no references and no document separator. Three YAML features don't survive the trip.
Comments are dropped by every converter above, since none of them can put a # line into JSON.
Anchors, aliases and merge keys get expanded into copies. Given this file:
defaults: &defaults
adapter: postgres
host: localhost
development:
<<: *defaults
database: dev_db
PyYAML, js-yaml 4 and yq produce a development object with adapter, host and database written out in full. js-yaml 5 and yaml keep a literal "<<" key instead, unless you enable merge support ({ merge: true } for yaml). Recent yq releases may also print a merge-anchor warning on stderr.
Multiple documents separated by --- need a loader that expects them. yaml.safe_load raises an error on a second document, so use yaml.safe_load_all. In js-yaml, load throws and loadAll returns an array. yq writes one JSON document per YAML document, and yq ea -o=json '[.]' file.yaml wraps them in a single array.
The honest limitation: a YAML to JSON to YAML round trip can't restore any of this. Comments, anchors and your original quoting are gone. Keep the YAML as the source of truth and generate the JSON from it. When you need to edit YAML in place, ruamel.yaml's round-trip mode keeps the comments; we confirmed it on the config above.
Converting Markdown Front Matter Between YAML and JSON
Front matter is the metadata block at the top of a Markdown file, usually YAML between --- lines. Our Markdown front matter guide covers its syntax and quoting rules. Some generators take other formats: Hugo accepts JSON and TOML front matter as well as YAML, and detects the format from the delimiters.
For a single block you don't need a script. The front matter generator runs in the browser, outputs YAML, TOML or JSON, and can parse existing front matter. Paste the file into its Existing document tab, click Load fields from document, then switch Format to JSON:
---
title: Release notes
date: 2026-11-11
draft: false
---
The output pane then shows the document with a JSON front matter block, where "date": "2026-11-11" is a string. It's built for one front matter block, not for nested config files or Kubernetes manifests, so use yq for those. If you want JSON shown as a readable table rather than another data file, see our guide to converting JSON to Markdown.
Questions About Converting YAML and JSON
Converting YAML to JSON takes one command, but the result depends on the parser: PyYAML follows YAML 1.1, while js-yaml 5, yaml and yq follow 1.2 rules. Quote values like NO and 1.10, keep the YAML as your source of truth, and check dates and merge keys after every conversion. To record those rules for your team, write them up in a README in our free Markdown editor, with no account needed.