Quick answer: JSON and XML both describe structured data as plain text. JSON is lighter and maps directly onto the objects and arrays used in most programming languages, which is why most web APIs use it. XML is more verbose but supports attributes, namespaces, comments and mixed text-and-markup content, so it remains common in document formats and older enterprise systems.
The same data in both formats
JSON
{
"book": {
"title": "Dune",
"year": 1965,
"authors": ["Frank Herbert"],
"inPrint": true
}
}
XML
<book inPrint="true">
<title>Dune</title>
<year>1965</year>
<authors>
<author>Frank Herbert</author>
</authors>
</book>
Notice that XML repeats every name in a closing tag, and that the list of authors needs a wrapper element. JSON has a literal array syntax.
Key differences
- Data types. JSON has strings, numbers, booleans, null, arrays and objects built in. In XML everything is text; types come from a schema or from the application reading it.
- Structure. JSON uses objects and arrays. XML uses nested elements plus attributes, so there are often two ways to store the same fact (
inPrint="true"or a child element). - Comments. XML allows comments. JSON does not.
- Size. Closing tags usually make XML larger than the equivalent JSON, although the difference shrinks when the data is compressed for transfer.
- Mixed content. XML can mix text and tags inside a paragraph, such as
some <b>bold</b> text. JSON has no natural way to do this, which is why XML-family formats suit documents. - Tooling. XML has a mature ecosystem: XSD schemas, XPath queries and XSLT transformations. JSON has JSON Schema and many query libraries, but the standards are newer and less uniform.
- Namespaces. XML supports namespaces to combine vocabularies without name clashes. JSON has no equivalent.
When to choose JSON
- Web and mobile APIs, where the data is consumed by JavaScript or similar languages.
- Configuration files and data exchange between services.
- Any case where compact, easy-to-read data matters more than document features.
When to choose XML
- Documents with text and markup mixed together.
- Systems or standards that already require it, such as many office file formats, RSS and Atom feeds, SVG and SOAP services.
- Cases that need formal schemas, namespaces or transformation pipelines.
Can you convert between them?
Simple, data-like structures convert cleanly. Conversions get ambiguous when XML uses attributes or mixed content, because JSON has no direct counterpart, and when JSON uses arrays, because XML needs a convention for repeated elements. Expect to agree on a mapping rather than assuming a lossless one.
If you work with JSON day to day, read how to validate JSON and fix common errors next.