XML vs JSON
JSON (JavaScript Object Notation) and XML are the two most widely used text formats for structured data. They can often describe the same information, but they were designed with different goals, and each is the better choice in different situations.
The same data, twice
<employees>
<employee id="7">
<name>Ines Duarte</name>
<skills>
<skill>SQL</skill>
<skill>Python</skill>
</skills>
<remote>true</remote>
</employee>
</employees>{
"employees": [
{
"id": 7,
"name": "Ines Duarte",
"skills": ["SQL", "Python"],
"remote": true
}
]
}Both are readable, self-describing and hierarchical. The JSON is shorter, and it has real numbers, booleans and arrays; in XML, 7 and true are just text until a schema or program says otherwise.
Side by side
| XML | JSON | |
|---|---|---|
| Syntax | Tags with names, attributes | Objects {}, arrays [], values |
| Data types | Text only (types come from a schema) | string, number, boolean, null, object, array |
| Arrays | Repeated elements | Native [...] |
| Attributes vs content | Two places for data | One |
| Comments | Yes <!-- --> |
No |
| Mixed content (text with markup) | Natural | Awkward |
| Namespaces | Yes | No |
| Schema / validation | DTD, XSD, RELAX NG, Schematron | JSON Schema |
| Query / transform | XPath, XQuery, XSLT | JSONPath, jq, plain code |
| Parsing in JavaScript | DOMParser + DOM navigation |
JSON.parse → plain objects |
| Size | Larger (closing tags) | Smaller |
Why JSON won for web APIs
In JavaScript, JSON is one call away from ordinary objects:
<!DOCTYPE html>
<html>
<body>
<script>
const jsonText = '{"employees":[{"id":7,"name":"Ines Duarte","skills":["SQL","Python"],"remote":true}]}';
const xmlText = `<employees><employee id="7"><name>Ines Duarte</name>
<skills><skill>SQL</skill><skill>Python</skill></skills><remote>true</remote></employee></employees>`;
// JSON: parse and use directly
const j = JSON.parse(jsonText).employees[0];
console.log('JSON:', j.name, j.skills.length, 'skills, remote =', j.remote, typeof j.remote);
// XML: parse, then navigate and convert types yourself
const e = new DOMParser().parseFromString(xmlText, 'application/xml').querySelector('employee');
const x = {
id: Number(e.getAttribute('id')),
name: e.querySelector('name').textContent,
skills: [...e.querySelectorAll('skill')].map(s => s.textContent),
remote: e.querySelector('remote').textContent === 'true',
};
console.log('XML :', x.name, x.skills.length, 'skills, remote =', x.remote, typeof x.remote);
console.log('Sizes:', jsonText.length, 'vs', xmlText.replace(/\s+</g, '<').length, 'characters');
</script>
</body>
</html>Where XML is still the better tool
- Documents, not just data: books, legal texts, technical manuals, office files. Text with inline markup (
<p>Press <key>Ctrl</key>+<key>S</key></p>) is natural in XML and clumsy in JSON. - Mixing vocabularies with namespaces (SVG inside XHTML, signatures inside invoices).
- Strict contracts between organisations, with mature schema tooling (banking, healthcare, government, aviation).
- Transformations of whole documents with XSLT, especially in publishing pipelines.
- Standards that require it: RSS, SVG, Office Open XML, SOAP, SAML, sitemaps, Android layouts.
Converting between them
There is no single "correct" mapping, because XML has things JSON lacks (attributes, mixed content, order between different element types). Here is one simple convention: attributes get an @ prefix, repeated elements become arrays, and text-only elements become strings.
<!DOCTYPE html>
<html>
<body>
<script>
function toJson(el) {
const obj = {};
for (const a of el.attributes) obj['@' + a.name] = a.value;
const kids = [...el.children];
if (kids.length === 0) {
const text = el.textContent.trim();
return el.attributes.length ? { ...obj, '#text': text } : text;
}
for (const k of kids) {
const v = toJson(k);
if (k.nodeName in obj) {
if (!Array.isArray(obj[k.nodeName])) obj[k.nodeName] = [obj[k.nodeName]];
obj[k.nodeName].push(v);
} else obj[k.nodeName] = v;
}
return obj;
}
const xml = `<employee id="7">
<name>Ines Duarte</name>
<skill>SQL</skill><skill>Python</skill>
<phone type="work">+351 21 000 0000</phone>
</employee>`;
const root = new DOMParser().parseFromString(xml, 'application/xml').documentElement;
console.log(JSON.stringify({ [root.nodeName]: toJson(root) }, null, 2));
</script>
</body>
</html>Note: This simple converter has a known weakness: an element that appears once becomes a string, but twice becomes an array. Real converters let you configure which elements are always arrays.
Choosing
| If you are… | Choose |
|---|---|
| Building a REST API for your own web or mobile app | JSON |
| Storing app settings read by JavaScript | JSON |
| Writing documents with rich inline markup | XML |
| Exchanging data under an industry standard | Whatever the standard says (often XML) |
| Producing graphics, feeds or sitemaps | XML (SVG, RSS, sitemap) |
Test yourself
Which data type does JSON have natively that XML doesn't?
- Text
- Numbers and booleans
- Elements
- Comments
Which is a strength of XML over JSON?
- Smaller file size
- Native arrays
- Mixed content and namespaces
- Faster
JSON.parse
Does JSON support comments?
- Yes, with
// - Yes, with
<!-- --> - No
- Only inside strings