Skip to content

Guide

Convert YAML to JSON in code

When the conversion belongs in a script or a build step rather than a browser tab, these are the equivalents.

By yamltojsonfree · Published · Updated

Python, Node.js, Go, and the command line

Each snippet reads input.yaml and prints formatted JSON. They aren’t interchangeable, though — the note under each one tells you which YAML version that library implements, and that difference can silently change your data.

Python

import json, yaml

with open("input.yaml") as f:
    data = yaml.safe_load(f)          # safe_load, never load()

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

PyYAML implements YAML 1.1, so `no` becomes False here — unlike the browser tool, which defaults to 1.2.

Node.js

import { readFileSync } from "node:fs";
import { load } from "js-yaml";

const data = load(readFileSync("input.yaml", "utf8"));
console.log(JSON.stringify(data, null, 2));

js-yaml v5 defaults to YAML 1.2 — the same engine and defaults the browser tool on this site uses.

Go

import (
    "encoding/json"
    "os"
    "sigs.k8s.io/yaml"
)

in, _ := os.ReadFile("input.yaml")
out, _ := yaml.YAMLToJSON(in)
os.Stdout.Write(out)

sigs.k8s.io/yaml converts through JSON tags, which is what Kubernetes itself uses.

Bash (yq)

# Single document
yq -o=json input.yaml

# Multi-document into a JSON array
yq -o=json -I=2 'select(document_index >= 0)' -N input.yaml

# Minified
yq -o=json -I=0 input.yaml

This is mikefarah/yq. The other yq (kislyuk) is a jq wrapper with different flags.

Three things to get right in a script

Use the safe loader. In Python, yaml.load() without an explicit loader can construct arbitrary Python objects from tagged YAML — which is code execution if the input isn’t yours. safe_load() parses plain data only, and there is almost never a reason to use anything else.

Know your YAML version. PyYAML reads YAML 1.1, so country: NO comes out as False; js-yaml v5 and Go’s Kubernetes-flavored parser read 1.2, so the same line stays a string. A pipeline that converts with one library and validates with another can disagree with itself. The full list of affected values is in the YAML 1.1 vs 1.2 guide.

Handle multi-document streams. Kubernetes and Helm output is usually several documents separated by ---. A plain load reads only the first one and silently drops the rest — use yaml.safe_load_all() in Python, loadAll() in js-yaml, or the yq invocation shown above to get every document.

Or skip the script entirely

For a one-off conversion, the free YAML to JSON converter does everything above in the browser: multi-document streams, anchors and merge keys, YAML 1.1 and 1.2 modes, and errors pinned to the exact line. Nothing is uploaded — the parser runs entirely on your machine.

References