Skip to content

XML ↔ JSON Converter — TypeScript source

Convert XML to JSON and back, preserving attributes. Validates input and reports errors clearly, runs entirely in your browser, with a shareable link to your exact input.

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

// XML <-> JSON conversion backed by `fast-xml-parser`. Attributes are preserved
// (the v5 default `ignoreAttributes: true` is overridden). XML is validated first
// so malformed input returns null instead of a lenient best-effort parse. The
// unit-test surface for the XML <-> JSON Converter tool.

import { XMLParser, XMLBuilder, XMLValidator } from 'fast-xml-parser';

const PARSER = new XMLParser({ ignoreAttributes: false, parseTagValue: true });
const BUILDER = new XMLBuilder({ ignoreAttributes: false, format: true, indentBy: '  ' });

/** Parse a well-formed XML string to pretty-printed JSON, or null if malformed. */
export function xmlToJson(xml: string): string | null {
  if (XMLValidator.validate(xml) !== true) return null;
  return JSON.stringify(PARSER.parse(xml), null, 2);
}

/** Build an XML string from a JSON string with an object/array root, or null if invalid. */
export function jsonToXml(json: string): string | null {
  let obj: unknown;
  try {
    obj = JSON.parse(json);
  } catch {
    return null;
  }
  if (obj === null || typeof obj !== 'object') return null;
  return BUILDER.build(obj);
}

Also available in 13 other languages

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