How to Parse XML to JSON in JavaScript
Use the browser's DOMParser for repeatable conversions and the visual tool when you just need the JSON once.
The native browser API for XML is good enough for almost every conversion. The only hard part is deciding how to represent attributes, text content, and repeated child elements when you collapse them into JSON.
1. Parse the XML string
const xml = `<users> <user id="1">Ada</user> <user id="2">Bea</user>
</users>`; const doc = new DOMParser().parseFromString(xml, 'application/xml');Always use application/xml. The text/html mode is more forgiving but normalizes tags in ways that break round-trips.
2. Walk the tree and emit JSON
function nodeToJson(node) { const result = {}; for (const attr of node.attributes || []) { result['@' + attr.name] = attr.value; } for (const child of node.children) { const value = child.children.length ? nodeToJson(child) : child.textContent.trim(); result[child.tagName] = result[child.tagName] ? [].concat(result[child.tagName], value) : value; } return result;
} const json = nodeToJson(doc.documentElement);The @attr prefix keeps attributes from colliding with child element names. The repeat-element check turns multiple siblings into an array automatically.
3. Decide what attributes mean
If your downstream consumer does not care about attributes, drop them. If you need them, the prefix convention above is the simplest option. Just be consistent across the codebase so consumers know what to expect.
When to switch to the browser tool
For a single payload, XML to JSON is faster than writing a parser. Paste the XML, copy the JSON. The same page handles namespaces and mixed content correctly.
To round-trip back to XML, pair it with JSON to XML. For the broader workflow, browse the Data Conversion Tools hub.