JSON and XML are both text formats for structured data, readable by people and programs. XML came first and was the default for web services in the 2000s; JSON took over for web APIs because it's smaller and maps directly onto the objects and arrays of programming languages. Here is the same record in both:
{
"user": {
"id": 7,
"name": "Ann Lee",
"active": true,
"roles": ["admin", "dev"]
}
}<user>
<id>7</id>
<name>Ann Lee</name>
<active>true</active>
<roles>
<role>admin</role>
<role>dev</role>
</roles>
</user>Minified, the JSON version is 72 bytes and the XML version 113, about 57% larger, mostly because every XML element name is written twice. In JSON, 7 is a number and true a boolean; in XML both are just text until something interprets them.
The main differences
| JSON | XML | |
|---|---|---|
| Data model | Objects, arrays and values | A tree of elements with attributes and text |
| Types | String, number, boolean, null, object, array | Everything is text unless a schema says otherwise |
| Lists | Arrays: ["a", "b"] | Repeated elements: <role>a</role><role>b</role> |
| Metadata | No separate concept | Attributes, e.g. <user id="7"> |
| Comments | Not allowed | Yes: <!-- … --> |
| Namespaces | No | Yes, to mix vocabularies in one document |
| Validation | JSON Schema | XSD, DTD, RELAX NG |
| In the browser | JSON.parse, built into JavaScript | DOMParser, then walk the DOM |
When to use JSON
- REST and GraphQL APIs, and anything a browser or mobile app consumes.
- Configuration and data files read by code, such as package.json or tsconfig.json.
- Storing documents in databases like MongoDB, PostgreSQL's jsonb or Elasticsearch.
- Logs and events, where small size and fast parsing matter.
When XML is still the better choice
- Documents with mixed text and markup, like books, legal texts or XHTML, which JSON represents awkwardly.
- Formats that are XML by definition: SVG, RSS and Atom, Office files, Android layouts, Maven's pom.xml.
- SOAP services and enterprise or government integrations that require XML and XSD validation.
- When you need namespaces to combine several vocabularies in one document.
Converting JSON to XML
Because XML has no arrays and no types, converting means making choices: what to call the root element, how to write lists, whether some values become attributes, and how to handle keys that aren't valid XML names (like 123name or first name). The JSON to XML converter does this as you type, escapes special characters, renames invalid keys and lists every rename, and lets you choose the root, attributes and array style. It runs in your browser, so the data stays on your device. Check the JSON with the JSON Validator first if the converter reports an error.