XML to JSON Converter
Convert XML documents into clean JSON objects.
Written by Anil Gautam · Updated
How does XML map to JSON here?
The root element becomes the single top-level key, and everything else nests below it. Attributes become keys starting with @, and text becomes a #text key even when the element has no attributes, so <to>Reader</to> turns into "to": {"#text": "Reader"}. Child elements become nested keys, with names kept exactly as written, so a tag such as order-line needs bracket notation in JavaScript. Empty elements become an empty string, or an object of their attributes if they have any. Indentation between tags, comments and the <?xml ?> declaration are dropped, and entities are decoded, so & arrives as &.
Take <order id="1042"><item sku="A1">Pen</item></order>. The JSON is {"order": {"@id": "1042", "item": {"@sku": "A1", "#text": "Pen"}}}, with attributes listed before child elements. Add a second item, <item sku="B2">Ink</item>, and item becomes an array of two objects. Code that reads this JSON has to accept both shapes, for example by wrapping a single object in an array before looping.
Why are numbers and booleans still strings?
Plain XML has no data types, so every attribute and text value arrives as a string. <qty>05</qty> becomes {"#text": "05"} and <ok>true</ok> becomes {"#text": "true"}. Convert types in your own code, where you know whether 05 is a quantity or a code that needs its leading zero. Reading a simple value always goes through #text: with the sample on this page, data.note.to["#text"] returns Reader, and data.note.heading["@priority"] returns high.
What gets lost, and why does parsing fail?
Mixed content keeps only its last run of text. <p>Hello <b>world</b> again</p> becomes {"#text": "again", "b": {"#text": "world"}}, and Hello disappears, so HTML-like markup converts badly; the HTML to Markdown Converter suits it better. CDATA survives only when it is the whole content of an element, and next to child elements it is dropped. Text is trimmed of surrounding whitespace.
Parsing uses your browser's built-in XML parser, which rejects anything that is not well-formed and reports the line and column of the first problem; the wording of that message differs between browsers. Common causes are a bare & (write &), an HTML tag such as <br> left open (write <br/>), mismatched closing tags and more than one root element. Namespace prefixes stay as written, so soap:Body remains soap:Body. To convert in the other direction, the JSON Formatter's Convert view exports XML.