Skip to content

TOML ⇄ JSON Converter — TypeScript source

Convert TOML to JSON and back. Tables, array-of-tables, and dotted keys round-trip; bare TOML dates stay date-only, datetimes become ISO-8601 strings. Swap carries the result into the input.

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

// Pure surface of the toml-json-converter tool (slug: toml-json-converter).
// Both directions over `smol-toml`. Edge contract for the Go twin: TOML dates
// become JSON ISO-8601 strings; mixed arrays keep order; JSON→TOML emits
// 2-space nested tables; non-representable JSON (NaN via parse it cannot be —
// but top-level non-objects ARE representable in TOML as bare values).
import { parse, stringify } from 'smol-toml';

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

/** TOML → pretty JSON (2-space). Dates serialize as ISO strings. */
export function tomlToJson(raw: string): ConvertResult {
  const text = raw.trim();
  if (!text) return { output: '', error: null };
  try {
    const parsed = parse(text);
    return { output: JSON.stringify(parsed, null, 2), error: null };
  } catch (e) {
    return { output: '', error: e instanceof Error ? e.message : 'Invalid TOML' };
  }
}

/** JSON → TOML (2-space nested tables). */
export function jsonToToml(raw: string): ConvertResult {
  const text = raw.trim();
  if (!text) return { output: '', error: null };
  try {
    const parsed = JSON.parse(text);
    return { output: stringify(parsed as never), 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 →