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
- XML elements can have attributes; JSON only has fields.
- An XML element can hold text and child elements at the same time (mixed content).
- XML doesn't say whether an element is a list or a single item; JSON arrays do.
- XML values are all text; JSON has numbers, booleans and null.
- XML has namespaces and keeps element order; JSON objects are unordered.
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
- Validate the XML first; a broken document produces broken JSON. The XML formatter shows where.
- Agree on one convention for attributes and text, and document it.
- List the elements that can repeat and treat them as arrays everywhere.
- Convert types explicitly instead of trusting guesses.
- For round trips (JSON back to XML), keep the
@and#textfields 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.