Data Formats
XML vs JSON: Differences, Examples, and When to Use Each
XML and JSON are both text formats for structured data, but they model that data differently. XML centers on elements, attributes and document order; JSON centers on objects, arrays and typed values.
Published
XML and JSON use different data models
XML represents a document as nested elements with optional attributes, text nodes, comments, processing instructions and namespaces. JSON represents values: objects, arrays, strings, numbers, booleans and null.
Because the models differ, conversion is a mapping decision rather than a character-for-character rewrite.
The same data in XML and JSON
This mapping keeps the XML attribute in a dedicated object. The text true remains a string unless the converter is explicitly allowed to infer scalar types.
XML:
<user id="42">
<name>Ada</name>
<active>true</active>
</user>
JSON:
{
"user": {
"@attributes": { "id": "42" },
"name": "Ada",
"active": "true"
}
}Types, order and repeated values
| Question | XML | JSON |
|---|---|---|
| Scalar types | Text unless a schema or application adds type rules | String, number, boolean and null are built in |
| Order | Child element order is significant to the document model | Array order is significant; object member order should not carry meaning |
| Repeated values | Repeated sibling elements | Explicit arrays |
| Metadata | Attributes and namespaces | Ordinary object members by convention |
Readability, size and tooling
- JSON is usually more compact for object-shaped application data.
- XML is more expressive for marked-up documents, mixed text and metadata attached as attributes.
- Both formats support validation, but their schema ecosystems and data models are different.
- Neither format is automatically secure: parsers still need size limits and safe configuration.
When to use XML or JSON
Choose JSON for web APIs, configuration and application state when the consumer naturally expects objects and arrays. Choose XML for document-oriented workflows, standards such as SOAP, namespace-qualified vocabularies, or contracts that distinguish attributes from elements.
When converting an established XML contract, decide how to preserve attributes, repeated siblings, namespaces and text before treating the JSON output as an equivalent representation.
Try the example
Convert one XML object to JSON
The example makes the attribute and text-value mapping visible.
<user id="42"><name>Ada</name><active>true</active></user>Expected result: Smart mapping groups id under @attributes and preserves text values as strings.
Convert a real document
See how XML maps to JSON
Paste your own XML, inspect its structure, and choose how attributes, repeated elements and scalar values should map.