The mismatch, stated plainly
XML and JSON do not describe the same universe, so no conversion is lossless in both directions. XML has attributes, namespaces, comments, processing instructions and ordered mixed content. JSON has objects, arrays, strings, numbers, booleans and null.
This converter makes three explicit choices:
| XML | JSON |
| --- | --- |
| Attribute | key prefixed with @ |
| Text beside attributes | key #text |
| Repeated element name | array |
Comments and processing instructions are dropped, because JSON has nowhere to put them.
The repeated-element trap
A response with one item produces an object; the same response with two produces an array. Code written against the one-item case then breaks on the second item — a classic production incident. If you consume converted XML, coerce to an array before using it, every time.
Everything stays local
The document is parsed by your browser, so an export containing customer records or invoice data never reaches a server.
Questions
How are attributes represented?+
Prefixed with @, so a currency attribute becomes the key @currency alongside #text for the element's own text. Without a prefix an attribute could collide with a child element of the same name, and the result would depend on document order — exactly the kind of bug that surfaces months later.
Why did one element become an array and another not?+
Because XML has no notion of a list: two sibling tags of the same name are just two elements. When a name repeats, the converter produces an array. When it appears once, it produces a value. If your consumer needs a stable shape, normalise it afterwards — this is a property of the mapping, not a choice.
Can I convert JSON back to XML?+
Yes, switch the direction. The object must have exactly one top-level key, because XML has exactly one root element. Keys starting with @ become attributes and #text becomes the element's text.
Which parser is used?+
The browser's built-in DOMParser. It handles namespaces, entities, CDATA and encoding declarations the way the specification says, which a hand-written parser in a web page would not.