GameParticles
Developer

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. 42 is a number and true is 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

FeatureJSONXML
SpecificationRFC 8259 and ECMA-404W3C XML 1.0, first published 1998
Data typesString, number, boolean, null, object, arrayText only, unless a schema assigns types
ListsNative arraysRepeated elements
AttributesNoneYes, name="value" on any element
NamespacesNoneYes, through xmlns
CommentsNot allowedAllowed
Mixed text and markupAwkwardNatural
Schema languageJSON SchemaDTD, XML Schema (XSD), RELAX NG
Query and transformJSONPath, jqXPath, XQuery, XSLT
Typical useREST APIs, config, logsDocuments, 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.

Tools in this guide

Frequently asked questions

What is XML?

XML (Extensible Markup Language) is a text format that wraps data in named opening and closing tags, such as <name>Ada</name>. It became a W3C Recommendation in 1998 and underlies formats including RSS, SVG, SOAP, sitemaps and the files inside Word and Excel documents.

Is JSON better than XML?

For sending data between programs, usually yes: JSON is shorter, maps directly to objects and arrays, and parses with one function call. XML is better for documents that mix text with markup and for systems that depend on schemas, namespaces or XSLT.

Is JSON faster than XML?

Generally. JSON has a smaller grammar and less text per value, so parsers tend to do less work and payloads are smaller. The exact difference depends on the parser and the data, and compression narrows the size gap considerably.

Can XML be converted to JSON?

Yes, but not uniquely, because JSON has no attributes. A common convention prefixes attribute names with @ and stores mixed text under #text. Repeated sibling elements become an array. Comments and processing instructions are normally dropped.

More developer guides

JSON Formatter
Developer · Format, validate and minify JSON with syntax highlighting.
↵
Base64 Encode / Decode
Developer · Encode text to Base64 or decode Base64 back to plain text.
↵
URL Encoder / Decoder
Developer · Encode or decode URL components and query strings.
↵
Hash Generator
Developer · Generate MD5, SHA-1, SHA-256 and SHA-512 hashes.
↵
UUID Generator
Developer · Generate UUIDs v4 (random) in bulk with one click.
↵
Regex Tester
Developer · Test regular expressions against text with live match highlighting.
↵
Word Counter
Text · Count words, characters, sentences, paragraphs and reading time.
↵
Case Converter
Text · Convert text between UPPER, lower, Title, camelCase, snake_case and more.
↵
List Sorter
Text · Sort, reverse, deduplicate and shuffle lists of text.
↵
Markdown Preview
Text · Write Markdown and see a live rendered preview side by side.
↵
Percentage Calculator
Numbers · Calculate percentages, increases, decreases and what % one number is of another.
↵
Color Converter
Colors · Convert colors between HEX, RGB, HSL and HSV instantly.
↵
Snake
Arcade · Eat food, grow longer, don't hit the walls. A timeless classic.
↵
2048
Puzzle · Slide tiles and combine them to reach the legendary 2048 tile.
↵
Word Grid
Puzzle · Guess the hidden five letter word in six tries using color clues.
↵
Sudoku
Puzzle · Fill the 9x9 grid with logic. Four difficulties from easy to expert.
↵
Minesweeper
Strategy · Use number clues to clear the minefield. Classic logic, three levels.
↵
Breakout
Arcade · Smash every brick with paddle and ball. Power-ups, combos, endless levels.
↵
Typing Practice
Casual · Build your WPM and accuracy with timed drills from 30 seconds to 5 minutes. Find your weak keys.
↵
TypeRunner
Arcade · Multiplayer typing race. Race friends by link, beat computer runners, or chase your own ghost.
↵
Typing Blocks
Arcade · Type each word before its wooden block lands. Miss, and the pile climbs toward the line.
↵
Bubble Shooter
Arcade · Aim, bank shots off the walls, and pop groups of three or more bubbles.
↵
Road Rush
Arcade · Race seven rivals through traffic and punch your way to the front.
↵