XML to JSON: How to Convert and When to Use Each Format
XML and JSON are the two most common data interchange formats on the web. While JSON has become the default for modern APIs and configuration files, XML remains deeply embedded in enterprise systems, SOAP web services, RSS feeds and many legacy applications. Converting between the two is a task most developers face sooner or later. In this guide, we will cover how XML and JSON differ structurally, how to convert between them correctly and the edge cases you need to watch for.
XML vs JSON: Structural Differences
Before converting, it helps to understand how each format represents data. JSON uses key-value pairs, arrays and primitive types (strings, numbers, booleans, null). XML uses a tree of elements with opening and closing tags, attributes and text content.
// JSON
{
"user": {
"name": "Alice",
"age": 30,
"active": true
}
}
<!-- XML -->
<user>
<name>Alice</name>
<age>30</age>
<active>true</active>
</user>
This simple example maps cleanly, but real-world XML has features that JSON does not: attributes, namespaces, mixed content (text interleaved with child elements), comments and processing instructions. These features make conversion less straightforward than it looks at first glance.
How XML Attributes Map to JSON
XML elements can have attributes, but JSON objects only have key-value pairs. The most common convention is to prefix attribute keys with @ or _ in the JSON output:
<!-- XML with attribute -->
<book isbn="978-0-13-468599-1">
<title>The Pragmatic Programmer</title>
</book>
// JSON result
{
"book": {
"@isbn": "978-0-13-468599-1",
"title": "The Pragmatic Programmer"
}
}
Different libraries use different conventions. Some use $ for text content and @ for attributes. Others use #text and -attributeName. The key is to pick a convention and stay consistent.
The Array Problem
This is the single biggest gotcha in XML to JSON conversion. XML does not have a native array type. Repeated sibling elements with the same tag name represent a list, but if there is only one element, most converters will output it as a single object instead of an array with one item:
<!-- Two items: converter outputs an array -->
<items><item>A</item><item>B</item></items>
{ "items": { "item": ["A", "B"] } }
<!-- One item: converter outputs a string -->
<items><item>A</item></items>
{ "items": { "item": "A" } }
This inconsistency can break your code if you always expect an array. The fix is to use a "force array" option that many conversion libraries provide, or to normalize the output in your code by wrapping single values in arrays.
Data Types and Type Loss
XML treats everything as text. The string <age>30</age> is a text node containing "30", not the number 30. When converting to JSON, a good converter will attempt to infer types: parsing "30" as a number, "true"/"false" as booleans and "null" as null. However, this inference is not always safe. A zip code like "00123" should remain a string, not be converted to the number 123. Be careful with automatic type coercion and test edge cases.
Converting in JavaScript
In the browser, you can use the built-in DOMParser to parse XML and then walk the DOM tree to build a JSON object. For Node.js, popular libraries include fast-xml-parser, xml2js and xmlbuilder2.
// Using DOMParser in the browser
const parser = new DOMParser();
const doc = parser.parseFromString(xmlString, "text/xml");
const root = doc.documentElement;
// Walk children and build JSON object
function xmlToJson(node) {
const obj = {};
for (const child of node.children) {
obj[child.tagName] = child.children.length
? xmlToJson(child)
: child.textContent;
}
return obj;
}
Converting in Python
Python's standard library includes xml.etree.ElementTree for parsing XML. For conversion, the xmltodict package is the most popular choice and produces OrderedDict objects that serialize directly to JSON:
import xmltodict, json
xml_string = "<user><name>Alice</name></user>"
result = xmltodict.parse(xml_string)
json_output = json.dumps(result, indent=2)
JSON to XML: Going the Other Way
Converting JSON to XML is generally simpler because JSON has a cleaner, more predictable structure. Each key becomes an element name and each value becomes the text content. Arrays are converted to repeated elements with the same tag name. However, there are some rules to keep in mind:
- Root element is required. JSON can have any value at the top level, but XML must have exactly one root element. If your JSON is an array, you need to wrap it in a root element.
- Key names must be valid XML. JSON keys can contain spaces, start with numbers or include special characters. These need to be sanitized or escaped for valid XML element names.
- Null values. XML has no null type. Common approaches include an empty element, an
xsi:nil="true"attribute, or omitting the element entirely.
When to Use XML vs JSON
Choose JSON when building REST APIs, SPAs, mobile apps or any modern web application. JSON is lighter, faster to parse and natively supported in JavaScript. Choose XML when working with SOAP services, RSS/Atom feeds, SVG graphics, Android layouts, Microsoft Office formats (OOXML) or any system that requires schema validation with XSD. Many enterprise integrations still use XML, so being comfortable with both formats is valuable.
Common Pitfalls
- Namespaces. XML namespaces (xmlns) add prefixes to element names. Some converters strip them, others preserve them as part of the key. Know how your tool handles them.
- CDATA sections.
<![CDATA[...]]>sections contain raw text that should not be parsed as XML. Make sure your converter extracts CDATA content as a plain string. - Comments and processing instructions. XML comments and PIs like
<?xml version="1.0"?>are typically dropped during conversion since JSON has no equivalent. - Order sensitivity. JSON object keys are unordered by specification, but XML element order is meaningful. If order matters, consider using JSON arrays instead of objects.
Convert XML and JSON instantly
Paste your XML or JSON data and convert between formats with a single click. All processing happens in your browser.
Open XML to JSON Converter