JSON vs XML

JSON replaced XML as the default for web APIs, but XML is still everywhere: office documents, SVG, RSS, SOAP services, Android layouts and build files. They are good at different things, and knowing why makes conversions between them far less painful.

Two different data models

JSON describes data structures: objects (unordered name/value pairs), arrays (ordered lists), strings, numbers, booleans and null. That maps directly onto the dictionaries, lists and scalars of every programming language, which is the main reason it won for APIs.

XML describes documents: a tree of elements, each with a name, optional attributes, and children that may be other elements or text, interleaved. The same order record might look like this in each:

{ "id": 1042, "status": "paid", "items": [{ "sku": "KB-01", "qty": 1 }] }
<order id="1042" status="paid">
  <items>
    <item sku="KB-01" qty="1"/>
  </items>
</order>

XML has more ways to say the same thing: status could be an attribute or a child element, and designers argue about which. JSON has exactly one way. On the other hand, XML can express things JSON cannot without inventing conventions, such as text with inline markup, comments, and processing instructions.

Types and values

In JSON, 1042 is a number, true a boolean and null a null, and every parser agrees. In XML everything is text: qty="1" is the string “1” until a schema or the application decides otherwise, and there is no built-in null. XML Schema (XSD) can declare that an attribute is an xs:integer or an element is nillable, and schema-aware tools then give you typed values, but plain parsers do not.

This difference is the first source of conversion bugs. Converting XML to JSON either keeps every value as a string, which is safe but awkward, or guesses types, which turns ZIP codes such as 02134 into the number 2134 and product codes such as 1E5 into 100000. Prefer converters that keep strings unless you supply a schema.

Features XML has that JSON lacks

  • Mixed content. <p>Press <kbd>Ctrl</kbd> to copy</p> mixes text and elements naturally. JSON needs an ad hoc structure for this, which is why documents (XHTML, DocBook, Office Open XML) stay in XML.
  • Attributes and namespaces. Namespaces let one document combine vocabularies without name clashes, such as SVG inside XHTML, or a SOAP envelope around a payload. JSON has no equivalent; JSON-LD’s @context is the closest convention.
  • Comments and processing instructions. XML allows <!-- comments -->. Standard JSON does not, which is why configuration formats like JSONC and JSON5 exist; see JSON with comments.
  • Mature document tooling. XPath for selecting nodes, XSLT for transforming documents, and XSD, RELAX NG and Schematron for validation, all standardised for decades.

JSON has caught up on the data side: JSON Schema handles validation (see JSON Schema basics), and JSONPath, standardised as RFC 9535, plus jq cover querying. The JSONPath cheat sheet shows the syntax side by side with familiar XPath ideas.

Size, speed and readability

JSON is usually smaller because it has no closing tags, and parsers for it are simpler and faster; browsers parse it natively with JSON.parse and response.json(). Compression narrows the size gap considerably, since repeated tag names compress well, so for most APIs the deciding factors are developer convenience and tooling rather than bytes on the wire.

Readability depends on the content. Deeply nested data structures are easier to scan as JSON; long text with formatting is easier as XML. Both become unreadable when minified, and both are easy to pretty-print: the JSON formatter and XML formatter indent a document without changing its meaning.

Security differences

XML parsers historically supported features that are dangerous on untrusted input:

  • External entities (XXE). A document can declare an entity that points at a file or URL, such as file:///etc/passwd, and a permissive parser will read it into the document, leaking files or making requests from the server.
  • Entity expansion (“billion laughs”). Nested entity definitions expand exponentially, so a few kilobytes of XML can consume gigabytes of memory.

Modern parsers disable external entities by default or provide a secure mode, but older libraries and some language defaults do not, so check yours. JSON has no entities, includes or references, so its parsers are much simpler to secure. The remaining JSON risks are resource limits (huge or deeply nested input), big numbers losing precision, duplicate keys, and prototype pollution when results are merged into objects carelessly.

Converting between XML and JSON

There is no single correct mapping, because the models differ. Every converter has to decide:

  1. Attributes. Common conventions prefix them, for example "@id": "1042", or put them under a separate key.
  2. Text next to attributes. <price currency="EUR">9.90</price> needs both, often written as {"@currency": "EUR", "#text": "9.90"}.
  3. One versus many. <items><item/></items> with one child looks the same as a single-valued element, so a naive converter produces an object for one item and an array for two. Code consuming the result then breaks on the day a list has exactly one entry. Good converters let you name elements that must always be arrays.
  4. Order and mixed content. JSON objects are unordered, so documents that depend on element order or mix text and tags lose information.
  5. Names. JSON keys can be anything, but XML names cannot start with a digit or contain spaces, so keys like "1st place" must be renamed.

Round trips are therefore rarely exact. Use XML to JSON to explore a feed or a SOAP response, and JSON to XML to feed a system that only accepts XML, then check the output with the XML validator before sending it.

Which one to choose

Choose JSON for web and mobile APIs, configuration consumed by programs, messages between services, and data stored in document databases. It is the expected default, and every language handles it with little ceremony.

Choose XML when the content is a document rather than a data structure, when you need namespaces to combine vocabularies, when an existing standard is defined in XML (SVG, RSS and Atom, SAML, SOAP, Office Open XML, sitemaps), or when partners require it.

In mixed environments, convert at the edge: accept or emit XML where a partner demands it, and keep JSON inside your own services.

Frequently asked questions

Is JSON faster than XML?

Usually, because JSON is smaller and simpler to parse, and browsers parse it natively. After compression, size differences shrink, so tooling and convenience tend to matter more.

Can JSON have attributes like XML?

No. JSON has only objects, arrays and values. Converters represent XML attributes with naming conventions such as an @ prefix on the key.

Does JSON support comments?

Standard JSON does not. XML supports comments natively; for JSON, use a dialect such as JSONC or JSON5 where comments are needed.

Why did my XML to JSON conversion produce an object instead of an array?

The element appeared only once, so the converter could not know it was meant to be a list. Configure the element as always-an-array, or normalise single values to arrays in your code.

Is XML more secure than JSON?

No. XML parsers need extra care because of external entities and entity expansion attacks. JSON parsers have fewer features and therefore fewer risks.

Related