XML and JSON
XML and JSON both store structured data as text. JSON has largely taken over web APIs, but XML is still everywhere: office documents, sitemaps, SVG graphics, Android layouts, RSS feeds and enterprise systems.
The same data, twice
<order id="1042" status="shipped">
<customer>Asha Verma</customer>
<items>
<item sku="KB-01" qty="1">Mechanical Keyboard</item>
<item sku="MS-07" qty="2">Wireless Mouse</item>
</items>
<total currency="INR">7499.00</total>
</order>{
"id": 1042,
"status": "shipped",
"customer": "Asha Verma",
"items": [
{ "sku": "KB-01", "qty": 1, "name": "Mechanical Keyboard" },
{ "sku": "MS-07", "qty": 2, "name": "Wireless Mouse" }
],
"total": { "amount": 7499.00, "currency": "INR" }
}What maps to what
| Idea | XML | JSON |
|---|---|---|
| a named value | an element or an attribute | a key |
| several of the same thing | repeated elements | an array |
| numbers and true/false | text, unless a schema gives it a type | real numbers, true, false, null |
| comments | <!-- ... --> | not allowed |
| text mixed with markup | natural: <p>Click <b>here</b></p> | awkward |
| namespaces | built in | none |
| querying | XPath | JSONPath, or code |
| validating | DTD, XML Schema | JSON Schema |
There's no single correct translation. Should an attribute become a key? Is one item element a single object or an array of one? Converters each decide differently.
Converting XML to JSON
The browser parses XML for you, so a converter is a short recursive function. Press Run and read the console:
<script>
const xml = `<order id="1042" status="shipped">
<customer>Asha Verma</customer>
<items>
<item sku="KB-01" qty="1">Mechanical Keyboard</item>
<item sku="MS-07" qty="2">Wireless Mouse</item>
</items>
<total currency="INR">7499.00</total>
</order>`;
function toJSON(el) {
const obj = {};
for (const attr of el.attributes) obj["@" + attr.name] = attr.value; // attributes get an @
const children = [...el.children];
if (children.length === 0) {
const text = el.textContent.trim();
return el.attributes.length ? { ...obj, "#text": text } : text;
}
for (const child of children) {
const value = toJSON(child);
if (child.tagName in obj) { // a repeat: make an array
if (!Array.isArray(obj[child.tagName])) obj[child.tagName] = [obj[child.tagName]];
obj[child.tagName].push(value);
} else {
obj[child.tagName] = value;
}
}
return obj;
}
const doc = new DOMParser().parseFromString(xml, "application/xml");
const root = doc.documentElement;
console.log(JSON.stringify({ [root.tagName]: toJSON(root) }, null, 2));
</script>Notice the decisions this converter makes. Attributes become keys starting with @, a convention many tools share. Repeated item elements become an array. And every value is still a string, "1" rather than 1, because XML has no idea that qty is a number. Without a schema, a converter can only guess.
Which should you use?
| Choose XML when | Choose JSON when |
|---|---|
| the data is a document: text with markup, like books or help pages | the data is records: objects, lists and values |
| you need namespaces, schemas with types, or XSLT | a JavaScript front end or web API consumes it |
an industry standard requires it: SOAP, RSS and Atom, SVG, sitemaps, Office files, Maven's pom.xml | you want a compact format that's quick to parse |
Both are good formats. Most developers use JSON day to day and meet XML in specific, important places.