How to Convert XML to JSON: Attributes, Arrays and Types

Last updated: · 5 min read

When a SOAP response, an RSS feed, an e-invoice or an export from an older system has to be handled in JavaScript, the first step is usually to turn the XML into JSON. The catch is that attributes, mixed content and repeated elements have no direct counterpart in JSON, and no standard says how to map them. The XML to JSON Converter uses the common "@name" and "#text" notation and reports the line number when the document is not well-formed. This guide explains the rules and spends most of its time on the two points that cause bugs in production code: every value arrives as a string, and a single element is not an array. The output in the example is the tool's real result.

Formula

Rules:
1. The document is read from start to end; the XML declaration, comments, processing instructions and the DOCTYPE are skipped.
2. The root element becomes the only key of the JSON object.
3. An element that contains only text becomes a string; an empty element becomes null.
4. Attributes are written under "@name" keys; the text of an element that has attributes goes into "#text".
5. Sibling elements with the same name are collected into an array; an element whose name occurs once is not an array.
6. & < > " ' and numeric character references are decoded; a CDATA section is taken as text verbatim.
7. All values are strings: no numbers, booleans or dates are inferred.

Input:
<order id="A-17">
  <customer>Kaya &amp; Co</customer>
  <item sku="P1">2</item>
  <item sku="P2">1</item>
  <note/>
</order>

Output:
{
  "order": {
    "@id": "A-17",
    "customer": "Kaya & Co",
    "item": [
      {
        "@sku": "P1",
        "#text": "2"
      },
      {
        "@sku": "P2",
        "#text": "1"
      }
    ],
    "note": null
  }
}

This is a parsing and mapping algorithm, not a formula. The tool checks the well-formedness rules of XML 1.0: a single root element, tags closed in the right order, quoted attributes that are not repeated. It does not validate against a DTD or an XSD, does not expand entities declared in a DOCTYPE and never loads external resources. The output is JSON indented with two spaces.

What the inputs mean

XML
The XML document to convert. It must be well-formed and have exactly one root element; the leading XML declaration is optional. Up to 1,000,000 characters and 200 nesting levels are processed.

Worked example: Converting an order document to JSON

  1. The root element <order> becomes the single key "order", and its id attribute is written as "@id": "A-17".
  2. <customer> holds nothing but text, so it is a plain string. The &amp; reference is decoded and the value is "Kaya & Co".
  3. The two <item> elements share a name, so "item" is an array. Each has both an attribute and text, which makes each entry an object with "@sku" and "#text".
  4. "#text": "2" is quoted. The tool does not assume that 2 is a number; convert it with Number() before doing arithmetic.
  5. The empty element <note/> becomes "note": null.

Result: The output is a JSON object whose "order" key holds "@id", "customer", a two-entry "item" array and "note" with the value null. The quantities are the strings "2" and "1".

🔀 XML to JSON Converter

Free, no sign-up; your data stays in your browser.

Open the calculator →

How to read the result

Harden the code that consumes this output in two places. First, arrays: had the order contained a single <item>, "item" would be one object rather than an array, and order.item.map(...) would throw. Check with Array.isArray and wrap the value before using it. Second, types: "120" is not 120, and the string "false" is truthy in JavaScript. Also note that the relative order of siblings with different names, and the position of text between tags in mixed content, are not carried into JSON; for document-style XML such as XHTML this conversion is the wrong tool. This is general information.

Common mistakes

  • Assuming a single element still arrives as an array. An element that occurs once is a plain value or object; your code has to handle both shapes.
  • Using numbers without converting them. "2" + "1" gives "21", not 3.
  • Using HTML entities such as &nbsp; in XML. Only the five predefined entities and numeric references are decoded; anything else fails with "invalid or undefined entity reference". Write &#160; for a non-breaking space.
  • Closing tags in the wrong order. For <b>1</c> the tool reports the line: "Line 2: closing tag </c> does not match <b>."
  • Expecting namespace prefixes to be stripped. A soap:Body element stays as the key "soap:Body", and the xmlns:soap declaration stays as "@xmlns:soap".
  • Looking for a difference between <a></a> and <a/>. Both become null; the distinction between an empty string and a missing value is not preserved.

Frequently asked questions

Why are numbers returned as strings?

XML carries no type information; <price>120</price> is just text. The tool does not guess, because turning a postcode such as "00123" or a long identifier into a number corrupts it. Decide which fields are numeric from your schema.

Why is a single element not an array?

The tool only knows what is in the document; without a schema it cannot tell that an element may repeat. A name that occurs twice gives an array, a name that occurs once gives a single value. Add an Array.isArray check in the consuming code.

Does the tool validate the XML against a schema?

No. It checks well-formedness only: the root element, matching tags, attribute syntax and entity references. DTD and XSD rules are not applied.

What happens to CDATA sections and comments?

CDATA content is added to the text as it stands, including any < and & characters. Comments and processing instructions are left out of the output.

If I convert the JSON back to XML, do I get the same document?

You get a structurally similar one, because the JSON to XML Converter reads the same "@name" and "#text" notation. Comments, the DOCTYPE, the original indentation and the order of differently named siblings do not come back.

The result is not exact or binding and is for information only; it is not an official document and cannot be used in official procedures. Confirm it with the competent authority or a professional before acting; no liability is accepted for losses arising from its use.

Sources

Choose your cookie preference to continue

Records the site needs to work (theme, language, favourites) stay in your browser.

This site is free and funded by ads.

With your consent, Google Analytics cookies measure visits and Google AdSense cookies are used to show ads; the data is processed on Google servers abroad.

If you reject, the site works just the same.

Cookie Policy · KVKK notice