XML to JSON: Bridging Two Worlds
XML was the dominant data format for APIs until JSON took over around 2010. But XML is still everywhere: SOAP APIs, RSS feeds, SVG files, Android layouts, Maven configs, and enterprise systems. Converting between them is a daily task.
The Mapping
<!-- XML -->
<user id="42">
<name>Alice</name>
<email>alice@example.com</email>
<tags>
<tag>admin</tag>
<tag>verified</tag>
</tags>
</user>
// JSON equivalent
{
"user": {
"@id": "42",
"name": "Alice",
"email": "alice@example.com",
"tags": {
"tag": ["admin", "verified"]
}
}
}The Tricky Parts
| XML Feature | JSON Challenge |
|---|---|
Attributes (id="42") | No equivalent — convention: prefix with @ |
| Single child vs array | One <tag> = string, two = array. Inconsistent! |
| Text + children mixed | <p>Hello <b>world</b></p> — no clean JSON mapping |
| Namespaces | xmlns:soap="..." — ugly as JSON keys |
| Comments | JSON has no comments |
Programmatic Conversion
// Node.js — fast-xml-parser
import { XMLParser } from 'fast-xml-parser';
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '@_',
isArray: (name) => ['tag', 'item'].includes(name),
});
const json = parser.parse(xmlString);# Python — xmltodict
import xmltodict, json
with open('data.xml') as f:
data = xmltodict.parse(f.read())
print(json.dumps(data, indent=2))JSON to XML (Reverse)
// Node.js
import { XMLBuilder } from 'fast-xml-parser';
const builder = new XMLBuilder({
attributeNamePrefix: '@_',
ignoreAttributes: false,
});
const xml = builder.build(jsonObj);Convert now: XML to JSON — paste XML, get clean JSON. Or try JSON to XML for the reverse.