XML to JSON Tutorial: Convert XML to JSON with Examples
Last updated:
Converting XML to JSON requires 4 structural decisions: how to represent XML attributes (as prefixed keys like @id or nested under _attr), how to handle text nodes with siblings (the #text convention), how to collapse single-item arrays, and how to map XML namespaces. XML elements with text content and attributes need 2 keys in JSON; elements with only text can collapse to a string. In JavaScript, fast-xml-parser converts XML to JSON in 1 line; in Python, xmltodict.parse() does the same. This guide covers the conversion rules, the 4 attribute strategies, and code examples for JavaScript, Python, and the command line.
Convert XML to JSON online
Paste any XML to get formatted JSON instantly — handles attributes, namespaces, and nested elements automatically.
Open XML to JSON ConverterHow XML elements map to JSON keys
Each XML element becomes a JSON key. The element's text content becomes the value. The root element is typically used as the top-level JSON object key.
<!-- XML -->
<person>
<name>Alice</name>
<age>30</age>
<active>true</active>
</person>// JSON
{
"name": "Alice",
"age": 30,
"active": true
}Note: numbers and booleans in text content are cast to their native JSON types when the converter can infer them unambiguously.
How repeated XML elements become JSON arrays
When multiple sibling elements share the same tag name, they are grouped into a JSON array. This is the main structural difference between XML and JSON.
<!-- XML -->
<bookstore>
<book>
<title>Learning XML</title>
<price>39.95</price>
</book>
<book>
<title>JSON at Work</title>
<price>49.99</price>
</book>
</bookstore>// JSON
{
"book": [
{ "title": "Learning XML", "price": 39.95 },
{ "title": "JSON at Work", "price": 49.99 }
]
}How empty XML elements map to JSON null
Self-closing tags and elements with no content map to null in JSON.
<!-- XML -->
<user>
<name>Bob</name>
<middleName/>
</user>// JSON
{
"name": "Bob",
"middleName": null
}Nested XML elements
Nested elements become nested JSON objects:
<!-- XML -->
<order>
<customer>
<name>Alice</name>
<email>alice@example.com</email>
</customer>
<total>199.99</total>
</order>// JSON
{
"customer": {
"name": "Alice",
"email": "alice@example.com"
},
"total": 199.99
}Convert XML to JSON in JavaScript
In the browser you can parse XML with the built-in DOMParser and walk the DOM recursively:
function xmlToJson(node) {
const children = Array.from(node.children)
// No child elements — return text content
if (children.length === 0) {
const text = node.textContent?.trim() ?? ''
if (text === '') return null
if (text === 'true') return true
if (text === 'false') return false
const num = Number(text)
if (!isNaN(num)) return num
return text
}
const obj = {}
for (const child of children) {
const key = child.tagName
const val = xmlToJson(child)
if (key in obj) {
if (!Array.isArray(obj[key])) obj[key] = [obj[key]]
obj[key].push(val)
} else {
obj[key] = val
}
}
return obj
}
const parser = new DOMParser()
const doc = parser.parseFromString(xmlString, 'text/xml')
const json = xmlToJson(doc.documentElement)
console.log(JSON.stringify(json, null, 2))Convert XML to JSON in Python
import xml.etree.ElementTree as ET
import json
def xml_to_dict(element):
children = list(element)
if not children:
text = (element.text or '').strip()
if text == '': return None
if text.lower() == 'true': return True
if text.lower() == 'false': return False
try: return int(text)
except ValueError: pass
try: return float(text)
except ValueError: pass
return text
result = {}
for child in children:
val = xml_to_dict(child)
if child.tag in result:
if not isinstance(result[child.tag], list):
result[child.tag] = [result[child.tag]]
result[child.tag].append(val)
else:
result[child.tag] = val
return result
root = ET.fromstring(xml_string)
data = xml_to_dict(root)
print(json.dumps(data, indent=2))Common pitfalls
- XML attributes are lost — simple converters only handle element content, not attributes. If your XML uses attributes heavily, you may need a custom mapping.
- Mixed content — XML elements with both text and child elements (common in HTML-like XML) don't map cleanly to JSON.
- Namespaces — XML namespaces (
xmlns:prefixes) are usually included verbatim in the JSON key names, which can be noisy.
Convert XML to JSON online
Use the XML to JSON converter to transform any XML document instantly. For the reverse, use the JSON to XML converter.
Frequently asked questions
How are XML attributes converted to JSON?
Simple converters ignore attributes; advanced ones use a convention like "@attributes" or "@" prefixes. For example, <user active="true"> might produce a key like @attributes containing the attribute values. Check your converter documentation for its attribute handling option.
What happens to XML namespaces in JSON?
Namespace prefixes appear verbatim in JSON key names (e.g., "soap:Body"), producing noisy output. Use a converter with a namespace-stripping option, or post-process the output to flatten or remove prefixed keys before using the JSON in your application.
How are repeated XML tags converted to JSON?
Multiple sibling elements with the same tag are grouped into a JSON array. If only one element exists, many converters produce a plain object instead of a single-element array — a common inconsistency. Look for a "force array" option to ensure consistent array output.
What does XML CDATA become in JSON?
CDATA sections are treated as plain text by the XML parser — the CDATA wrapper is stripped. The text content becomes a regular JSON string, with any characters needing escaping handled automatically. No special treatment is required.
How do I convert XML to JSON in JavaScript?
In the browser, use DOMParser with text/xml and walk the DOM. In Node.js, use fast-xml-parser (widely used, supports attribute options) or xml2js. For simple XML without attributes, a custom recursive DOM walker is also clean and dependency-free.
What about XML comments in JSON?
XML comments are ignored by XML parsers and do not appear in the parsed tree. They are always lost during conversion because JSON has no comment syntax. Comments in XML are documentation, not data, so this is rarely a practical problem.
Recommended reading
- Designing Data-Intensive Applications (2nd Edition) — Martin Kleppmann & Chris RiccominiThe modern classic on data systems — encoding formats, schemas, replication, and stream processing.
- API Design Patterns — JJ GeewaxBattle-tested patterns for designing consistent, scalable JSON APIs — from a Google API architect.
As an Amazon Associate, Jsonic earns from qualifying purchases.