anon accelerate
← Other blogs

YAML to JSON in Python: a five-line script and the traps to avoid

PyYAML reads it, the json module writes it, and quoting fixes most of the surprises.

To convert YAML to JSON in Python, load the file with PyYAML's yaml.safe_load and write the result with the standard json module. That takes about five lines. For a single file you only need to look at once, the free AyeTab converter does the same job in a browser tab with no code and no upload.

The script

Install PyYAML first:

pip install pyyaml

Then:

import json
import sys

import yaml

with open(sys.argv[1]) as f:
    data = yaml.safe_load(f)

print(json.dumps(data, indent=2, default=str))

Run it as python yaml2json.py config.yaml > config.json. The indent=2 gives readable output; drop it when the JSON goes into a request body and size matters. Keys keep the order they had in the YAML file, since Python dicts preserve insertion order.

Why safe_load and not load

PyYAML's own README tells you to use yaml.safe_load when you do not trust the input. The plain loader can build arbitrary Python objects from tags inside the file, which is not something you want from a config file that came out of a ticket, a vendor or a pull request. safe_load sticks to plain types: dicts, lists, strings, numbers, booleans and null, which map cleanly onto JSON.

Three traps, and the fix for each

Trap What happens Fix
Dates An unquoted date loads as a Python date, and json.dumps raises a TypeError Pass default=str, or quote dates in the YAML
Plain words as booleans PyYAML parses YAML 1.1, where yes, no, on and off become true or false Quote those values in the source file
Several documents in one file safe_load expects one document and complains at the --- Use yaml.safe_load_all and dump a list

The boolean one causes the most confusion in operations work. A feature flag file with enabled: on, or a list of country codes that includes NO, will not come out the way it reads. If you need YAML 1.2 behaviour, where only true and false count, use a parser that implements 1.2 instead.

For multi-document files such as Kubernetes manifests, the change is small:

docs = list(yaml.safe_load_all(f))
print(json.dumps(docs, indent=2, default=str))

Writing the output to a file

Printing to standard output keeps the script composable, but some teams prefer the script to write next to the source. Swap the last line for:

from pathlib import Path

out = Path(sys.argv[1]).with_suffix(".json")
out.write_text(json.dumps(data, indent=2, default=str))

Add ensure_ascii=False to json.dumps if the YAML holds accented names or other non-ASCII text and you want them written as is rather than as escape sequences.

When not to write Python at all

A script makes sense when the conversion repeats: a build step, a CI check, a migration across hundreds of files. For anything shorter there are faster routes.

  • Command line. yq, a single Go binary, converts with yq -o json file.yaml and fits into shell pipelines.
  • Browser. AyeTab gives you a YAML pane and a JSON pane, converts both ways, and copies the result with one click. It is free, needs no account, and parses everything locally, so an internal config file stays on your machine. Once the page loads it works offline too.

The Python route still wins when you need to change the data on the way through, such as filtering keys, merging files or checking values, since you already have the parsed dict in hand.

Keep the quick version close

If you convert files a few times a week, the AyeTab Chrome extension puts the same converter, and the rest of its developer tools, on your new tab and in a side panel. Ctrl+K or Cmd+K opens a command palette that finds the tool by name.

FAQ

Which Python library converts YAML to JSON? PyYAML reads the YAML and the built-in json module writes JSON. Use yaml.safe_load for files you did not write.

How do I convert a YAML file with several documents? Use yaml.safe_load_all, collect the documents into a list and dump that list as a JSON array.

Can I convert YAML to JSON without Python? Yes. Use yq on the command line, or paste the file into AyeTab's free browser converter.

Originally published on claudegpt.si