Web & Dev

JSON vs XML Comparison

JSON and XML compared — syntax, tooling, size, and where each still shines.

At a glance

AspectJSONXML
SyntaxBraces / brackets / colonsNested tags
SizeCompactVerbose
Data typesString, number, bool, null, array, objectAll values are strings
CommentsNot allowed (JSON5 allows)Yes
SchemaJSON SchemaXSD, DTD
NamespacesNoYes (xmlns)
AttributesNo (everything is a key)Yes
Mixed contentAwkwardNatural
TransformationsAd-hocXSLT, XPath
ToolingUbiquitous — every languageHeavy but mature
ReadabilityHigher (usually)Lower at scale

When to pick which

  • JSON: web APIs, config, mobile, most new systems.
  • XML: document-centric data (Office OOXML, DocBook, SVG), SAML, SOAP, finance (FIXML, XBRL), healthcare (HL7), government mandates.
  • YAML (3rd option): human-editable config (K8s, CI). More readable than JSON, pickier parser.
  • Protocol Buffers / Avro: binary formats — smaller and faster than either, at the cost of requiring schemas for decode.

Worked example: the same record

One person record in JSON: {"name":"Ada","age":36}, which is 23 bytes. The same record in XML: <person><name>Ada</name><age>36</age></person>, which is 46 bytes, twice as large, because every value carries an opening and closing tag. Compression such as gzip narrows the gap a great deal, since the repeated tags compress well, so measure the compressed size before deciding that size matters.

The types also differ. In the JSON above, 36 is a number and a parser returns it as one. In XML, 36 is text until a schema or your code says otherwise. On the other hand, JSON numbers have no defined precision: many parsers read them as 64-bit floating point, which represents whole numbers exactly only up to 253 (9,007,199,254,740,992). Larger identifiers, such as some database IDs, should be sent as strings.

Common mistakes

  • Adding comments to JSON. The standard (RFC 8259) has none; a parser will reject them. Use a field, or JSON5 or YAML for configuration files.
  • Assuming key order. JSON objects are unordered by definition; do not rely on the order of keys.
  • Wrong encoding. RFC 8259 requires JSON exchanged between systems to be UTF-8. Legacy encodings cause mojibake.
  • Parsing untrusted XML with defaults. Some XML parsers resolve external entities, which can leak files or cause denial of service; disable DTD and entity expansion.
  • Converting blindly. XML attributes, repeated elements and mixed text have no single JSON form, so a round trip can lose information.

Notes

  • XML is better at mixed content (e.g., "

    Hello world

    "). JSON needs convention (e.g., objects with "_text" and "children").
  • JSON parsing is typically 2–10× faster than XML at equivalent data size.
Was this article helpful?