CodeMIRAI
0 XP

XML and JSON

2 min read 1 runnable example Quiz included

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

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>
JSON
{
  "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

IdeaXMLJSON
a named valuean element or an attributea key
several of the same thingrepeated elementsan array
numbers and true/falsetext, unless a schema gives it a typereal numbers, true, false, null
comments<!-- ... -->not allowed
text mixed with markupnatural: <p>Click <b>here</b></p>awkward
namespacesbuilt innone
queryingXPathJSONPath, or code
validatingDTD, XML SchemaJSON 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:

HTML
<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 whenChoose JSON when
the data is a document: text with markup, like books or help pagesthe data is records: objects, lists and values
you need namespaces, schemas with types, or XSLTa JavaScript front end or web API consumes it
an industry standard requires it: SOAP, RSS and Atom, SVG, sitemaps, Office files, Maven's pom.xmlyou 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.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.