Skip to content

YAML ⇄ JSON Converter — TypeScript source

Convert YAML to JSON and back, both directions in one tool — swap carries the result straight into the input. Anchors and merge keys resolve on the way in; JSON emits canonical 2-space YAML on the way out.

This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Pure surface of the yaml-json-converter tool (slug: yaml-json-converter).
// Both directions are parse→stringify over the `yaml` package, pinned here so
// the Go CLI twin reproduces the same edge contract: YAML anchors/merges are
// RESOLVED into plain JSON; JSON→YAML emits 2-space canonical YAML; dates in
// YAML 1.1 (like 2024-01-15) become strings only if quoted — the yaml package
// types unquoted dates as strings unless a schema opts in, which we do not.
import { parse, stringify } from 'yaml';

export type ConvertResult =
  | { output: string; error: null }
  | { output: ''; error: null }
  | { output: ''; error: string };

/** YAML → pretty JSON (2-space). Empty input yields empty output. */
export function yamlToJson(raw: string): ConvertResult {
  const text = raw.trim();
  if (!text) return { output: '', error: null };
  try {
    const parsed = parse(text, { merge: true });
    return { output: JSON.stringify(parsed, null, 2), error: null };
  } catch (e) {
    return { output: '', error: e instanceof Error ? e.message : 'Invalid YAML' };
  }
}

/** JSON → canonical YAML (2-space, no wrap). Empty input yields empty output. */
export function jsonToYaml(raw: string): ConvertResult {
  const text = raw.trim();
  if (!text) return { output: '', error: null };
  try {
    const parsed = JSON.parse(text);
    return { output: stringify(parsed, { indent: 2, lineWidth: 0 }), error: null };
  } catch (e) {
    return { output: '', error: e instanceof Error ? e.message : 'Invalid JSON' };
  }
}

Also available in 1 other language

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in several languages — the same contract, ported. Compare all languages side by side →