How to Convert XML to JSON

How to Convert XML to JSON

Converting XML to JSON is something you do when you have a SOAP response, an RSS feed, or a config file and you want plain JSON to work with in JavaScript. The mapping is mostly intuitive, but XML has a few features that JSON does not, so the conversion needs some conventions. Here is how it works and what to watch for.

How XML to JSON mapping works

Each XML element becomes a JSON key, and its contents become the value. A simple element like this:

<book>
  <title>Dune</title>
  <year>1965</year>
</book>

becomes:

{ "book": { "title": "Dune", "year": "1965" } }

Note that 1965 comes through as a string. XML has no types, so everything is text unless you decide to coerce numbers and booleans yourself afterward.

The tricky parts

Three XML features have no direct JSON equivalent, so the converter has to pick a convention.

  • Attributes. XML attributes (<book id="42">) have nowhere natural to go in JSON. The common convention is to nest them under a key like @attributes or _attr. So <book id="42"> becomes { "book": { "@attributes": { "id": "42" } } }. Different libraries use different prefixes, so check which one yours uses.
  • Repeated elements become arrays. If a parent has several children with the same tag, those repeat into a JSON array. The catch: when there is only one child, you get a single object, not an array of one. If your code expects an array, normalize it before you loop.
  • Text content alongside attributes. An element that has both attributes and text content, like <price currency="USD">9.99</price>, cannot be a plain string. It needs a wrapper, usually with the text under a key like #text: { "price": { "@attributes": { "currency": "USD" }, "#text": "9.99" } }.

Namespaces (<ns:book>) are also awkward. Most converters keep the prefix as part of the key name (ns:book), which is usually what you want, but it makes the keys uglier to access in JavaScript.

Convert XML to JSON in your browser

The XML to JSON Converter handles all of these conventions for you and runs entirely client side, so a private SOAP response or internal config file never leaves your machine.

  1. Open the XML to JSON Converter.
  2. Paste your XML, or load it from a file.
  3. Read the JSON output, with attributes and repeated elements handled automatically.
  4. Copy the result into your JavaScript project.

Because it parses with the browser’s built-in XML support, there is no upload step and nothing is sent to a server.

Paste your XML, mind the attributes and arrays, and copy clean JSON.

← All posts