JSON vs XML
The two formats model different things. Converting between them is not a translation; it is a series of decisions, and every converter has to make them.
Last reviewed
Do it now
Different models
JSON models data: objects, arrays and scalars, with a small closed set of types. XML models documents: elements that can carry attributes, contain other elements, contain text, or contain both at once, all inside namespaces.
Neither is a subset of the other. XML has no array. JSON has no attribute, no namespace, no comment, no processing instruction, no document root name, and no way to mix text and children.
The four decisions every converter makes
- Attributes. XML has them and JSON does not, so they get folded into keys — commonly with a prefix such as @ or a nested "attributes" object.
- Repeated elements. Two <item> children obviously form an array; one <item> child is ambiguous, and a naive converter turns it into a single object. The same document with one row then produces a different shape from the same document with two.
- Text alongside children. <p>Hello <b>there</b></p> has no JSON equivalent, so the text goes into a key such as "#text".
- The root. Every XML document has exactly one root element; JSON has none. Converting JSON to XML means inventing a root name.
<order id="9912" xmlns:m="urn:meta">
<item sku="A-1">2</item>
<note>Ship <em>fast</em></note>
</order>{
"order": {
"@id": "9912",
"item": { "@sku": "A-1", "#text": "2" },
"note": { "#text": "Ship ", "em": "fast" }
}
}Types are lost in one direction
XML text nodes have no types — everything is a string unless a schema says otherwise. So XML to JSON either produces strings everywhere, or guesses, and guessing turns a phone number starting 0 into a number, a version string into a float, and the word "true" in a comment field into a boolean.
Prefer strings and convert deliberately, or turn type inference on with your eyes open.
Which to use
For a new API, JSON: less ceremony, smaller payloads, faster parsers, and a type system that maps onto every modern language.
XML still wins where documents genuinely are documents, where a validating schema and namespaces are contractual, or where the ecosystem is already there — SOAP services, publishing formats, office file formats, and long-lived enterprise integrations.
Keep reading
- JSON vs YAML — YAML is a superset of JSON, which makes conversion in one direction lossless and in the other direction a decision about what to discard.
- JSON vs CSV — CSV holds rows of text. JSON holds a typed tree. Every conversion between them either flattens something or invents something.