Free, independent guides since 2010

Code

JSON and XML compared: when to use which

The differences between JSON and XML, with examples: syntax, data types, attributes and namespaces, schemas, tooling, and when each format is the better choice for websites and APIs.

<guide section="Code" type="guide" read="1 min"/>

If you build websites, you meet both formats: JSON in APIs and configuration files, XML in sitemaps, RSS feeds and SVG images. They describe structured data in different ways. Our dom4j guides cover working with XML in Java; this page compares the two formats.

The same data in both formats

XML
<book id="b1" lang="en">
  <title>Web hosting explained</title>
  <price currency="EUR">19.95</price>
  <tags><tag>hosting</tag><tag>beginners</tag></tags>
</book>
JavaScript
{
  "id": "b1",
  "lang": "en",
  "title": "Web hosting explained",
  "price": { "amount": 19.95, "currency": "EUR" },
  "tags": ["hosting", "beginners"]
}

Key differences

JSONXML
SyntaxCompact, objects and arraysTags, more verbose
Data typesStrings, numbers, booleans, null, arrays, objectsEverything is text unless a schema says otherwise
AttributesNo (just properties)Yes
NamespacesNoYes
Mixed content (text with markup)AwkwardNatural
SchemasJSON SchemaXSD, DTD, RELAX NG
QueryingJSONPath, codeXPath, XSLT
CommentsNot allowedAllowed

When to choose JSON

  • Web APIs and JavaScript applications.
  • Configuration files for modern tools.
  • Structured data on web pages (JSON-LD, see structured data).

When to choose XML

  • Standards that require it: sitemaps, RSS/Atom, SVG, e-invoicing formats.
  • Documents with mixed text and markup.
  • Strict validation and long-term archiving.
  • Integrations with enterprise systems.

Frequently asked questions

Is XML outdated?

No, it is just less fashionable for web APIs. XML remains the standard for sitemaps, feeds, SVG, office file formats, e-invoicing and many industry data exchanges.

Can I convert XML to JSON?

Yes, but not always one-to-one: attributes, namespaces and mixed text content have no direct JSON equivalent, so you must decide how to map them.