DEV Community

Avinash Verma
Avinash Verma

Posted on

How to Convert YAML to JSON in JavaScript and Python (the type traps to avoid)

YAML and JSON describe the same data, so converting sounds trivial — until an unquoted yes becomes true and a ZIP code loses its leading zero. Here's how to convert YAML to JSON correctly in JavaScript and Python, and the type traps to watch for.

JavaScript (js-yaml)

import yaml from 'js-yaml';
const data = yaml.load(yamlString);
const json = JSON.stringify(data, null, 2);
Enter fullscreen mode Exit fullscreen mode

Python (PyYAML)

import yaml, json
data = yaml.safe_load(yaml_string)
print(json.dumps(data, indent=2))
Enter fullscreen mode Exit fullscreen mode

Parse YAML into a native object, then re-serialize as JSON. That's the whole conversion — the bugs live in the details.

Trap 1: type coercion

YAML reads unquoted scalars aggressively:

  • yes, no, on, off become booleans
  • 1.10 becomes the number 1.1 (trailing zero gone)
  • 007 becomes the integer 7 (leading zeros gone)
  • 2024-01-01 becomes a date, not a string

If a value must stay a string — version numbers, ZIP codes, country codes — quote it: zip: "07030".

Trap 2: use the safe loader

Python's yaml.load() can construct arbitrary objects and is an RCE risk on untrusted input. Always use yaml.safe_load(). (js-yaml's default load is safe as of v4.)

Trap 3: multi-document files

A file with --- separators holds multiple documents. safe_load reads only the first — use safe_load_all() in Python or yaml.loadAll() in JS, then emit a JSON array.

Trap 4: anchors and aliases

YAML's &anchor / *alias references expand at parse time, so the JSON output inlines the duplicated data. Expected, but it can balloon the payload.

When you just need it converted once

For a one-off — a CI config, a Kubernetes manifest, a docker-compose.yml — you don't need a script. jsonviewertool.com/yaml-to-json converts it in the browser, 100% client-side, and the reverse JSON to YAML is there too.

Takeaway

The conversion is one function call; the bugs come from YAML's helpful-but-surprising coercion. Quote anything that must stay a string, use the safe loader, and handle multi-document files explicitly.

Top comments (0)