Mapping XML to JSON
XML has things JSON does not: attributes, mixed text and elements, repeated elements without a list wrapper. Every converter has to choose a mapping. This one uses the most common convention, the same one used by many XML libraries:
- each element becomes a key with its name;
- attributes become keys prefixed with
@; - an element that has only text becomes that text, while one with attributes and text gets a
#textkey; - an element that appears more than once under the same parent becomes an array.
Numbers and true/false in text and attributes are converted to JSON types; anything else stays a string.
Worked example
<book id="42" lang="en"><title>Dune</title><author>Frank Herbert</author><tag>sf</tag><tag>classic</tag></book>
becomes {"book": {"@id": 42, "@lang": "en", "title": "Dune", "author": "Frank Herbert", "tag": ["sf", "classic"]}}, written over several lines on the page.
How this works
The page checks that the XML is well formed while reading it into tokens, then builds the JSON with a stack: each start tag opens an object, attributes are added as @name keys, text and CDATA are decoded and added as #text, and each end tag attaches the finished object to its parent, turning repeated names into arrays. Objects with only text collapse to that text. Comments, the XML declaration and DOCTYPE are dropped. Use JSON to XML for the reverse. Everything runs in this tab.
Frequently asked
Why is one element an array and another an object?
Elements that appear several times under the same parent become arrays; single ones do not. This is the usual mapping, so check for both shapes in code.
How are attributes shown?
As keys starting with @, such as @id.
What happens to namespaces?
Prefixes stay in the key, such as soap:Envelope. Namespace declarations appear as @xmlns attributes.
Is my XML uploaded?
No. Everything runs in your browser.
Sources
- W3C — Extensible Markup Language (XML) 1.0, Fifth Edition
- RFC 8259 — The JavaScript Object Notation (JSON) Data Interchange Format
- Wikipedia — XML
Reviewed Oct 17, 2026 · test vectors fixtures/dev/xml-to-json/