All articles
165 articles · updated weekly See our Tools
All articles
Comparisons

JSON vs XML: Differences, Examples and When to Use Each

JSON vs XML in one table: types, comments, namespaces, schema and parsing, with tested examples and the cases (SOAP, ISO 20022, RSS) where XML still wins.

JSON vs XML: Differences, Examples and When to Use Each
COVER · Comparisons

Every time someone new joins an enterprise integration project and meets XML for the first time, the reaction is the same: "why does this still exist?" And every time someone tries to use JSON for a document with namespaces, metadata and a strict schema, the question flips. Choosing between the two isn't about fashion; it's about understanding where each format was designed to live.

This post starts with a table of the differences between JSON and XML, shows the same data in both formats, queried and transformed with real tools (I ran every example), and ends with a practical decision. If you want the JSON basics first — syntax, the six types, common mistakes — the post What Is JSON covers that.

Differences between JSON and XML

Aspect JSON XML
Nature data format (RFC 8259) markup language (W3C XML 1.0)
Types string, number, boolean, null, object, array everything is text; types come from a schema (XSD)
Lists native array [...] repeated elements
Attributes none; everything is key and value attributes and elements, with different semantics
Mixed content not supported supported (<p>text <b>bold</b> text</p>)
Comments not allowed (JSONC and JSON5 are extensions) <!-- comment -->
Namespaces none; JSON-LD uses @context native (xmlns)
Schema JSON Schema XSD, DTD, RELAX NG
Query and transform jq, JSONata, JSONPath XPath, XQuery, XSLT
Size smaller uncompressed larger; with gzip the gap almost disappears
Dominant use REST APIs, JS tooling config, events tax/fiscal documents, SOAP, feeds, document formats

The rest of the post explains the rows that weigh most in the decision.

The same data in both formats

{
  "user": {
    "id": 42,
    "name": "Rafael",
    "active": true
  }
}
<user>
  <id>42</id>
  <name>Rafael</name>
  <active>true</active>
</user>

Without closing tags, JSON is smaller. But the most important difference isn't visual: in JSON, 42 is a number and true is a boolean. In XML, both are text until someone says otherwise.

import json
data = json.loads('{"active": true, "value": 42.5}')
print(type(data["active"]), type(data["value"]))
# <class 'bool'> <class 'float'>

import xml.etree.ElementTree as ET
root = ET.fromstring('<item><active>true</active><value>42.5</value></item>')
print(repr(root.find('active').text), repr(root.find('value').text))
# 'true' '42.5'  ← strings; converting them is your job

That isn't a flaw in XML: it was designed for documents, where content is text. With an XSD, the schema declares that value is xs:decimal and schema-aware tools type the data. Without a schema, you convert by hand.

Which is easier to read, JSON or XML?

For data — records, lists, small configs — JSON is usually more readable: less noise, structure visible through indentation, explicit arrays. For documents, XML wins: text with markup in the middle (<p>Pay by <date>12/10</date></p>) is natural in XML and clumsy in JSON. XML also allows comments, which helps people editing by hand; plain JSON doesn't, and json.loads('{"a": 1 /* c */}') fails with a syntax error.

For files humans edit all the time, neither is the best choice: YAML or TOML exist for that. If you need to feed a YAML file into a system that only speaks JSON, the YAML to JSON converter handles it.

Size: verbosity matters less than it looks

I generated the same list of 1,000 users in both formats, without whitespace, in Python 3.12. Uncompressed, the XML came to 74,301 bytes against 45,294 for JSON — 64% larger. With gzip, which is how almost every HTTP response travels, it was 5,336 against 5,201 bytes: a 3% difference. Repeated tags compress extremely well.

XML's real cost isn't bytes, it's tooling complexity: DOM, XPath, namespaces, how the parser handles entities. That last one has a security impact: XML parsers that resolve external entities are exposed to XXE, a class of vulnerability that doesn't exist in JSON. Disable DTDs and external entities when reading third-party XML.

What XML has that JSON doesn't

Attributes and mixed content. An element can carry attributes and content at the same time:

<price currency="BRL" type="retail">149.90</price>

In JSON that becomes an object with separate fields ({"value": 149.90, "currency": "BRL", "type": "retail"}). Fine for data; for marked-up text, such as DocBook or DITA, the distinction between attribute and content carries real meaning.

Namespaces. Two vocabularies can share one document without name collisions:

<order xmlns:fin="http://finance.example.com"
       xmlns:log="http://logistics.example.com">
  <fin:amount>500.00</fin:amount>
  <log:weight>2.3</log:weight>
</order>

Plain JSON has nothing like it. The standardized answer is JSON-LD, a W3C Recommendation that maps keys to vocabularies through @context — the format Google reads for structured data. Beyond that, it's prefix conventions.

A mature schema language. XSD expresses type inheritance, element order and complex cardinalities, with decades of tooling in regulated domains. JSON Schema covers the vast majority of API validation and is simpler to adopt; the post on JSON Schema in REST APIs shows how to use it, and the JSON Schema validator helps test a schema against a payload.

Querying and transforming: XSLT and what exists on the JSON side

A common claim — one this post used to make — is that XSLT has no equivalent in the JSON world. That isn't true. There are established languages for querying and transforming JSON, and XSLT 3.0 itself reads JSON. To show it, the same order in both formats:

{"order": {"id": 1001, "items": [
  {"sku": "A1", "qty": 2, "price": 49.9},
  {"sku": "B7", "qty": 1, "price": 120.0}]}}
<order id="1001">
  <item sku="A1" qty="2" price="49.9"/>
  <item sku="B7" qty="1" price="120.0"/>
</order>

The order total in each tool (all of them returned 219.8):

# jq 1.7.1
jq '[.order.items[] | .qty * .price] | add' order.json

# JSONata 2.2 (JavaScript)
$sum(order.items.(qty * price))
<!-- XSLT 3.0 over the XML (SaxonC-HE 13.1) -->
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:template match="/">
    <xsl:value-of select="sum(//item/(@qty * @price))"/>
  </xsl:template>
</xsl:stylesheet>

And the same XSLT 3.0 over the JSON, using parse-json() from the specification:

<xsl:value-of select="sum(parse-json(unparsed-text($input))?order?items?*!(?qty * ?price))"/>

What XML still has that's different is a single, widely adopted W3C standard for document transformation — XSLT, with XPath and XQuery around it. In JSON, jq rules the command line and JSONata shows up in integration tools, but each is its own project.

Where XML is still the right choice

Brazilian electronic invoices (NF-e). Brazil's tax authorities (SEFAZ) require digitally signed XML, validated against the schemas published on the NF-e portal. "I'd rather use JSON" is not an option.

SOAP. Envelope, header, body and fault are XML by definition, and so is the WSDL describing the service. If you integrate with a SOAP web service from a bank, a government or an ERP, it's XML.

International payments. The industry's current standard is ISO 20022 (the "MX" messages), in XML. On the Swift network, coexistence with the old MT messages — which were field-based text, not XML — ended for cross-border payment instructions on November 22, 2025. Meanwhile, Open Finance Brasil exposes REST APIs with JSON. Both worlds coexist.

Healthcare. This one is easy to get wrong: HL7 v2, still widely used in hospital systems, is in its usual encoding pipe-delimited | text, not XML. XML shows up in HL7 v3 and CDA. FHIR, the modern standard, supports both JSON and XML.

Document formats. .docx, .xlsx and .pptx are Office Open XML (ECMA-376): a ZIP of XML files. .odt is OpenDocument, a different standard, also ZIP with XML. DocBook and DITA are pure XML.

Feeds and legacy integrations. RSS and Atom are XML. So are ESBs and enterprise services built on SOAP; the message queue itself (IBM MQ, for example) doesn't care about the payload format, but the systems at each end do. To read a minified XML from any of these, the XML formatter indents it and shows the structure.

Practical decision

Scenario Use
New REST API JSON
Microservices and events JSON
NF-e, NFS-e and fiscal documents XML
SOAP integration XML
ISO 20022 payments XML
Document with marked-up text XML
RSS/Atom feed XML
Config edited by humans YAML or TOML
Strict contract validation XML + XSD or JSON + JSON Schema
Legacy system that already speaks XML XML (the rewrite isn't worth it)

The general rule: if you control both sides and are starting from scratch, JSON. If the other side already exists and speaks XML, or the data is a document, XML — no drama.

Frequently asked questions

Will JSON completely replace XML?

No. JSON became the standard for new APIs, and XML concentrated where the ecosystem and the rules already exist: tax, payments, healthcare, document formats, feeds. ISO 20022, for instance, just became the standard for international payments — in XML.

Which is easier to read?

For data, JSON: less noise and explicit arrays. For documents with marked-up text, XML. For configuration humans edit, YAML or TOML, which allow comments and have less punctuation than either.

Is XML with a schema safer than JSON?

The format doesn't guarantee safety; validating input does. XSD is more expressive than JSON Schema in some areas, but JSON Schema covers almost all API validation. On parser security, JSON has the edge: no entities or DTDs, so XXE doesn't exist. To validate JSON step by step, see how to validate JSON.

How do JSON and XML handle dates?

Neither has a date type in the base format. In JSON, a date is a string, and ISO 8601 ("2026-06-13T10:00:00Z") is a convention; JSON Schema has "format": "date-time". In XML it's also text, but XSD defines xs:dateTime, which schema-driven tools type automatically.

The choice is about context

JSON won APIs because the tradeoff is clear: native types, direct parsing, less friction. XML stays where it was built to be: documents, established protocols, and domains with mandatory schemas. No size argument settles the question once gzip is involved, and the idea that JSON lacks transformation tools is a myth. Start with JSON when you get to choose; accept XML when the other side, the law or the data itself asks for it. For inspecting payloads day to day, I use the JSON Formatter — especially when an API returns a minified blob.

RD
Author
Rafael Duarte
Backend developer with a background in fintech and B2B SaaS — worked on teams that scaled APIs from zero to millions of requests. Carries enough production scars to hold strong opinions on tools, patterns and architecture decisions. Not an academic: he read the UUID RFC when he had to choose between v4 and v7 for a write-heavy table.
View profile