Convert XML to JSON in JavaScript

How XML-to-JSON conversion works in JavaScript, what it changes in your data, where it loses information, and when keeping XML is the better choice.

Turning XML into JSON in JavaScript is usually done so data from an XML feed, configuration file or legacy API can be used with ordinary objects and JSON tooling. The conversion looks simple, but XML and JSON describe data differently. Before relying on a converter, it helps to know what is preserved, what is reshaped and what is quietly dropped.

Is the conversion suitable for your use?

Converting is a good fit when the XML is record-like: elements containing other elements or short text values, with attributes used as simple metadata. In that case you gain direct property access, easy serialization with JSON.stringify, and compatibility with tools that expect JSON.

The decisive tradeoff is that there is no single standard mapping from XML to JSON. Every converter makes choices about attributes, repeated elements, text and whitespace, and those choices determine the shape your code has to handle. The output is only as predictable as the mapping rules you pick and test against your real data.

Keep the original XML, or treat it as text, when any of the following matter: document-style content where text and inline elements are interleaved, exact element order, comments or processing instructions, digital signatures computed over the XML bytes, or validation against an XML schema. JSON can carry a lossless encoding of these, but the result is usually harder to read than the XML itself.

What the conversion actually changes

An XML-to-JSON conversion is a structural change to stored data, not a visual or formatting effect. The XML text is parsed into a tree of nodes, and that tree is rebuilt as JavaScript objects, arrays and strings. Character content is decoded along the way: entity references such as & become the characters they represent, and CDATA sections become plain text.

In browsers, the built-in DOMParser can parse XML into a document tree. Node.js does not include DOMParser, so server-side code typically uses a third-party parser package. The example below uses the browser approach and a deliberately simple mapping so each decision is visible.

function xmlToJson(node) {
  const obj = {};

  for (const attr of node.attributes) {
    obj["@" + attr.name] = attr.value;
  }

  for (const child of node.childNodes) {
    if (child.nodeType === Node.TEXT_NODE || child.nodeType === Node.CDATA_SECTION_NODE) {
      const text = child.nodeValue.trim();
      if (text) obj["#text"] = (obj["#text"] || "") + text;
    } else if (child.nodeType === Node.ELEMENT_NODE) {
      const value = xmlToJson(child);
      if (child.nodeName in obj) {
        if (!Array.isArray(obj[child.nodeName])) {
          obj[child.nodeName] = [obj[child.nodeName]];
        }
        obj[child.nodeName].push(value);
      } else {
        obj[child.nodeName] = value;
      }
    }
  }

  return obj;
}

const xml = '<book id="42" lang="en"><title>Dune</title><author>Frank Herbert</author></book>';
const doc = new DOMParser().parseFromString(xml, "application/xml");

if (doc.getElementsByTagName("parsererror").length) {
  throw new Error("Invalid XML");
}

const root = doc.documentElement;
const result = { [root.nodeName]: xmlToJson(root) };
console.log(JSON.stringify(result, null, 2));

Following the function's rules by hand, that input produces the structure below. This is traced from the code, not a recorded test run, so confirm it in your target environment.

{
  "book": {
    "@id": "42",
    "@lang": "en",
    "title": { "#text": "Dune" },
    "author": { "#text": "Frank Herbert" }
  }
}

The parse-error check matters because DOMParser does not throw on malformed XML. It returns a document containing a parsererror element instead, so code that skips the check can silently convert an error message into JSON.

Where meaning can shift or be lost

XML feature | What a typical conversion does | Risk
Attributes | Stored as prefixed keys such as @id | Different converters use different prefixes, or merge attributes with child elements
Repeated elements | One occurrence becomes an object, several become an array | The same field changes type depending on the data
Values | Everything stays a string, so "42" is not the number 42 | Converters that guess types can turn identifiers like "007" into 7
Whitespace | Often trimmed or ignored | Meaningful spacing in text content disappears
Mixed content | Text pieces are concatenated apart from inline elements | Sentence structure and order are lost
Comments and processing instructions | Usually dropped | Information stored there is gone
Namespaces | Prefixes stay in names such as dc:title | Two prefixes for the same namespace produce different keys

The repeated-element problem causes the most bugs. If one book has a single author and another has two, code that reads book.author must handle both an object and an array. A common fix is to declare which element names should always become arrays, and to normalize values to the expected types after conversion rather than letting the converter guess.

Trimming text in the example is also a choice, not a neutral default. It removes the indentation whitespace found between elements in pretty-printed XML, but it also strips leading and trailing spaces inside real text values.

Will the result stay readable and usable when copied or shared?

The output of JSON.stringify is plain text, so it copies and pastes like any other text. Passing an indentation argument, as in JSON.stringify(result, null, 2), makes it readable in editors, logs and code reviews; omitting it gives compact single-line output that is better for transmission but hard to scan.

  • Encoding: JSON exchanged between systems is expected to be UTF-8, so if the source XML declared another encoding, make sure it was decoded correctly before conversion.
  • Escaping: quotation marks, backslashes and control characters in text are escaped by JSON.stringify, so pasted output may look different from the original XML text while representing the same characters.
  • Round trips: converting the JSON back to XML will not reproduce the original document unless the mapping preserved order, attributes, comments and whitespace.
  • Downstream tools: consumers that expect numbers or consistent arrays will need the normalization step described above.

Accessibility and search are not usually affected, because both formats are plain text data rather than visual styling. The practical readability concern is for people: deeply nested objects with @ and #text keys can be harder to follow than the original XML. If people will read the result directly, consider flattening simple text-only elements to plain string values.

Evidence gaps

No benchmarks, library comparisons or tested outputs were supplied for this review. The behavior described is based on the general design of XML, JSON, DOMParser and JSON.stringify. Specific converter libraries differ in their default mappings and options, so check their documentation and test them with a representative sample of your own XML, including repeated elements, empty elements, attributes and any mixed content, before depending on the output shape.