XML to JSON conversion: the decisions that matter

Updated 22 October 2026 · first published 10 January 2026 · 6 min read · By the JSON XML Editor team

Converting XML to JSON looks simple until you meet attributes, repeated elements and namespaces. XML has features JSON doesn't, so every converter makes choices. Knowing them helps you get JSON that your code can rely on.

Where XML and JSON differ

Attributes

The common convention, and the one the XML to JSON converter on this site uses, is to prefix attribute names with @:

<person id="123" name="Ada">
  <age>36</age>
</person>

{ "person": { "@id": "123", "@name": "Ada", "age": "36" } }

Text next to attributes

When an element has attributes and text, the text needs a field of its own, usually #text:

<price currency="EUR">99.99</price>

{ "price": { "@currency": "EUR", "#text": "99.99" } }

Repeated elements become arrays, single ones don't

<items><item>Apple</item><item>Banana</item></items>
{ "items": { "item": ["Apple", "Banana"] } }

<items><item>Apple</item></items>
{ "items": { "item": "Apple" } }

This is the classic trap: the same field is an array in one response and a string in another, and code that loops over it breaks. Fix it where you consume the data (always wrap the value in an array if it isn't one), or use a converter that lets you list the elements that must always be arrays.

Data types

A converter that only sees XML can't know whether <zip>01234</zip> is a number or text, and guessing breaks leading zeros and long IDs. Keeping values as strings (as above) is the safe default; convert the fields you know are numbers or booleans in your code, or use the XML Schema if there is one.

Namespaces

Prefixed names such as soap:Envelope are usually kept as they are, with the xmlns declarations as attributes:

{ "soap:Envelope": { "@xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/", "soap:Body": { } } }

If your code shouldn't depend on prefixes (they can change while the namespace stays the same), strip them in one place after converting.

A checklist

  1. Validate the XML first; a broken document produces broken JSON. The XML formatter shows where.
  2. Agree on one convention for attributes and text, and document it.
  3. List the elements that can repeat and treat them as arrays everywhere.
  4. Convert types explicitly instead of trusting guesses.
  5. For round trips (JSON back to XML), keep the @ and #text fields so JSON to XML can rebuild attributes.

In code, popular libraries are xml2js and fast-xml-parser (Node.js), xmltodict (Python) and Jackson's XmlMapper (Java). Check their options for attribute prefixes and forced arrays.

Try it: XML to JSON · JSON to XML · XML Formatter. Free, no sign-up.

More articles