Developer Documentation
TypeScript
Updated September 19, 2026

Convert XML to JSON in TypeScript

Parse XML and convert it to JSON using an explicit mapping convention in TypeScript.

XML can represent attributes, mixed text, namespaces, repeated elements, and ordering in ways JSON cannot represent directly. Pick a library and a stable mapping convention, then test it with real documents.

Quick Start#

The following example uses the standard TypeScript API or a widely used package for this task.

Using xml2js#

TypeScript
1// npm install xml2js2import { parseStringPromise } from "xml2js";34const value: unknown = await parseStringPromise(xml, {5  explicitArray: false,6  trim: true,7});89const json: string = JSON.stringify(value, null, );

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Typed boundary#

TypeScript
1const value: unknown = await parseStringPromise(xml, { explicitArray: false });2// Validate/narrow `value` before treating it as a domain object.

Important Notes#

XML parser output is runtime data; TypeScript interfaces do not validate it. Narrow or schema-validate before use.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement XML → JSON in other languages: