JSON vs XML: Differences, Examples and When to Use Each
JSON vs XML compared side by side: the same record in both formats, how attributes and namespaces work, and which format wins for APIs, documents and config.
Updated
JSON and XML are both text formats for structured data. JSON represents data as objects, arrays and typed values with very little punctuation; XML wraps every piece of data in named tags and adds attributes, namespaces and a deep toolset for validation and transformation. JSON is the default for web APIs, while XML remains the better fit for documents and for ecosystems built around schemas.
The same data in both formats
One user record, first as XML:
<user id="42"><name>Ada Lovelace</name><active>true</active><roles><role>admin</role><role>beta</role></roles></user>
And as JSON:
{"user": {"id": 42, "name": "Ada Lovelace", "active": true, "roles": ["admin", "beta"]}}
Three differences are visible straight away:
- Every XML element is named twice, once to open and once to close. JSON names each key once, so it is shorter.
- JSON has types.
42is a number andtrueis a boolean. In XML both are just text until a schema or the reading program says otherwise. - JSON has a real array. In XML a list is simply an element that happens to repeat, so a parser cannot tell whether one
<role>is a single value or a list of length one.
Side by side
| Feature | JSON | XML |
|---|---|---|
| Specification | RFC 8259 and ECMA-404 | W3C XML 1.0, first published 1998 |
| Data types | String, number, boolean, null, object, array | Text only, unless a schema assigns types |
| Lists | Native arrays | Repeated elements |
| Attributes | None | Yes, name="value" on any element |
| Namespaces | None | Yes, through xmlns |
| Comments | Not allowed | Allowed |
| Mixed text and markup | Awkward | Natural |
| Schema language | JSON Schema | DTD, XML Schema (XSD), RELAX NG |
| Query and transform | JSONPath, jq | XPath, XQuery, XSLT |
| Typical use | REST APIs, config, logs | Documents, feeds, SOAP, office file formats |
Attributes
XML gives you two places to put a value: as an attribute on the tag, or as content between the tags. <price currency="USD">9.99</price> uses both. The usual convention is that attributes carry metadata about the element and child elements carry the data itself, but the language does not enforce that, and two teams will often model the same record differently.
Attributes have limits. Each can appear only once per element, holds only a text value, and cannot contain nested structure. JSON has no equivalent, because everything is a key with a value. The record above would become {"price": {"currency": "USD", "value": 9.99}}, with the designer choosing the key names.
Namespaces
Namespaces solve a problem JSON simply does not address: mixing vocabularies from different authors in one document. A namespace ties a tag prefix to a unique URI, declared with xmlns. In <svg:rect xmlns:svg="http://www.w3.org/2000/svg"/> the svg: prefix says this rect is the SVG one, not some other format's rectangle.
That is how an Atom feed can carry embedded XHTML, or a SOAP envelope can carry a payload from any business schema, without name clashes. It is also the feature most responsible for XML's reputation as verbose and fiddly. JSON APIs avoid the problem by convention, with each API defining its own keys.
What XML can do that JSON cannot
- Mixed content.
<p>Press <kbd>Enter</kbd> to continue.</p>interleaves text and markup. This is what XML was designed for, and it is clumsy in JSON. - Comments and processing instructions inside the data.
- Mature validation. XSD can state that an element is required, appears between one and five times, and holds a date in a set range.
- Transformation. XSLT converts an XML document into another XML document, HTML or text using a stylesheet rather than program code.
- Document order. The sequence of elements is always significant, which matters for prose.
What JSON does better
- Size. Less markup means fewer bytes for the same data.
- Direct mapping. JSON's objects and arrays match the dictionaries and lists in nearly every programming language, so parsing gives you usable data in one call. XML parsing gives you a tree of nodes to walk.
- Simplicity. The entire JSON grammar fits on a single page, so parsers in different languages behave very consistently.
- A smaller attack surface. XML parsers that resolve external entities are open to XXE attacks, and nested entity definitions enable the "billion laughs" denial of service. Hardened parsers turn these features off; JSON never had them.
When each wins
Choose JSON for REST and GraphQL APIs, browser and mobile clients, configuration files, log lines and document databases. If you are designing something new and have no outside constraint, JSON is the usual answer. What a JSON file is covers the format from the beginning.
Choose XML, or more often accept it, when:
- The format is already defined as XML: RSS and Atom feeds, SVG, sitemaps, SOAP services, SAML, Android layouts, Maven build files, and the DOCX and XLSX office formats.
- The content is a document with inline markup rather than a set of records.
- A partner or regulator requires validation against an XSD, as is common in banking, healthcare and government data exchange.
The choice is rarely about taste. Most of the time the system on the other end has already decided, and your job is to convert cleanly.
Converting between them
Because the two models differ, conversion needs conventions, and it helps to know which ones your tool uses. The JSON to XML Converter works in both directions and detects which format you pasted.
Going from XML to JSON, it stores attributes as keys prefixed with @, keeps text that sits beside attributes or child elements under #text, and turns repeated sibling elements into an array. Text that looks like a number or a boolean becomes one. Going from JSON to XML, it wraps the result in a <root> element with an XML declaration, writes each key as an element, and writes each array entry as an <item> element. It produces elements only, so if the target system expects attributes or namespace declarations, add those by hand afterwards.
Two cautions apply to any converter. A single child element converts to a single value rather than a one-item array, so code reading the JSON must cope with both shapes. And a round trip does not return the original document: comments, attribute-versus-element choices and the original root name are not preserved.
Before converting JSON, run it through the JSON Formatter to confirm it is valid; a stray trailing comma is the usual reason a conversion fails. How to format and validate JSON lists the common errors.
Try it
Paste an XML response or a JSON payload into the JSON to XML Converter to see the same data in the other format, with attributes shown as @ keys. It is the quickest way to get a feel for how the two models line up before you write the mapping code.