JSON & Data
How to Parse XML into Clean JSON: Attributes, Arrays and Text Nodes Explained
Parse XML into clean JSON in the browser. Learn how attributes, repeated tags and text nodes map, with a worked example and the shape-shifting gotcha.
Try the toolXML to JSON →Turning verbose XML into workable JSON
Plenty of APIs — payment gateways, government data feeds, older SOAP services, RSS — still answer in XML. In a JavaScript or TypeScript codebase that is awkward: you cannot dot into an XML string the way you can with a parsed object. Converting XML to JSON gives you a structure you can traverse, map and type. The tricky part is that XML carries information JSON has no direct slot for — attributes, repeated elements, and text mixed with child nodes — so the conversion needs clear, predictable rules.
The conventions used
The XML to JSON tool parses your input with the browser's built-in DOMParser — the same engine your browser uses for real documents — and walks the tree with these rules:
- Attributes become keys prefixed with
@, soid="42"turns into"@id": "42". - Repeated child tags collapse into a JSON array.
- A leaf element with only text and no attributes collapses straight to its string value.
- Text that sits alongside child elements is kept under a
#textkey. - The root element name is preserved as the top-level key.
A worked example
This XML:
<user id="42">
<name>Ada</name>
<roles>
<role>admin</role>
<role>editor</role>
</roles>
</user>parses into:
{
"user": {
"@id": "42",
"name": "Ada",
"roles": {
"role": [
"admin",
"editor"
]
}
}
}The id attribute became @id, the single <name> collapsed to a string, and the two <role> elements became an array.
Gotchas worth knowing
- The shape depends on the data. One
<role>yields a string; two yield an array. Code that consumes the JSON should tolerate both, because the same source can produce either depending on how many children appear. - Everything is a string. XML has no types, so
<count>5</count>becomes"5", not5. Convert numbers and booleans yourself after parsing. - Namespaces are preserved. A tag like
<soap:Envelope>keeps its prefix as the JSON key"soap:Envelope". - Malformed XML fails loudly. A missing closing tag or a stray unescaped
&produces a parse error rather than silent, half-broken output.
Next steps
Once you have JSON, you can pretty-print it with the JSON Formatter, or turn a representative response into typed interfaces with the JSON to TypeScript tool so your editor autocompletes the fields.
Conclusion
XML to JSON conversion unlocks legacy and SOAP data for modern code, as long as you understand the conventions — @ for attributes, arrays for repeats, strings for everything. Paste your XML, pick an indent, and you get a clean object to work with, entirely in your browser with no upload.