How to Convert JSON to XML (Online, Python, and JavaScript)

JSON and XML describe the same kind of data, but they disagree on almost every detail: JSON has arrays and a handful of scalar types, XML has elements, attributes, namespaces, and a single mandatory root. That mismatch is why a “quick” JSON to XML conversion turns messy the moment your data has a list in it. This guide covers how the mapping actually works, the fastest way to convert JSON to XML online, and how to do it in Python and JavaScript, along with the gotchas that trip people up.

The fastest route: a browser converter

For a one-off conversion, an online tool beats writing code. Paste your JSON into the JSON to XML converter and it produces well-formed XML with a root element you choose, your preferred indentation, and an optional XML declaration. Because it runs entirely in your browser, the data never leaves your machine, which matters when the JSON came from a production API.

If the JSON will not convert, it is almost always invalid rather than genuinely unconvertible. Run it through the JSON parser to find the exact syntax error first, or format it so you can see the structure before you convert. Once you have XML, the XML formatter will re-indent or validate it.

How JSON maps to XML

Every converter has to make the same handful of decisions. Knowing them tells you what to expect from the output.

Here is the shape of a typical conversion:

{
  "user": {
    "id": 1,
    "roles": ["admin", "dev"]
  }
}

becomes:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <user>
    <id>1</id>
    <roles>admin</roles>
    <roles>dev</roles>
  </user>
</root>

Notice the array turned into two <roles> elements under <user>, and everything sits inside one <root>.

Convert JSON to XML in Python

Python has no JSON to XML converter in the standard library, but two small packages cover almost every case. xmltodict round-trips cleanly and expects a single top-level key to act as the root:

import json
import xmltodict

with open("data.json") as f:
    data = json.load(f)

xml = xmltodict.unparse({"root": data}, pretty=True)
print(xml)

If your JSON is a top-level array, wrap it so there is one root and one repeating child, for example {"root": {"item": data}}. For more control over the root name and attribute handling, dicttoxml is the other common choice:

from dicttoxml import dicttoxml

xml = dicttoxml(data, custom_root="root", attr_type=False)

Set attr_type=False unless you actually want type="str" attributes on every element, which most consumers do not. Both libraries install with pip and run offline.

Convert JSON to XML in JavaScript

In the browser or Node, a short recursive function handles the common case without a dependency:

function jsonToXml(obj, name) {
  if (obj === null) return `<${name}/>`;
  if (Array.isArray(obj)) {
    return obj.map(item => jsonToXml(item, name)).join("");
  }
  if (typeof obj === "object") {
    const inner = Object.keys(obj)
      .map(k => jsonToXml(obj[k], k))
      .join("");
    return `<${name}>${inner}</${name}>`;
  }
  const text = String(obj)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");
  return `<${name}>${text}</${name}>`;
}

const xml = jsonToXml(JSON.parse(input), "root");

That covers objects, arrays, primitives, and null. For production use with namespaces, attributes, or CDATA, reach for a library such as fast-xml-parser and its XMLBuilder, which is more robust than hand-rolled string building.

The gotchas that bite

A few things go wrong often enough to plan for:

JSON or XML: which should you use?

If you control both ends, JSON is usually the lighter choice for web APIs and config, and it is easier to parse in most languages. XML earns its place where you need schemas (XSD), namespaces, attributes, comments, or mixed content, and in ecosystems that already speak it: SOAP services, RSS and Atom feeds, sitemaps, and older enterprise systems. Converting JSON to XML is usually about meeting one of those systems where it is, not a permanent migration. If you are still getting comfortable with the format underneath all this, the guide on what JSON is covers its data types and structure.

Frequently asked questions

How do I convert JSON to XML without writing code?
Paste the JSON into the JSON to XML converter, pick a root element and indentation, and copy or download the XML. It runs in your browser, so nothing is uploaded.

How are JSON arrays handled in XML?
Each array item becomes a repeated element sharing the array’s key name, because XML has no array type. A two-item array produces two sibling elements.

Why does my converted XML fail to parse?
Usually a missing root element or an invalid tag name. Make sure the whole document is wrapped in one root, and that keys with spaces or leading digits are sanitized. If the source JSON itself is invalid, the JSON parser will point to the error.

Can I convert the XML back to JSON?
Not with this tool, which is one-way. In code, xmltodict.parse in Python reverses the process. To inspect large JSON before converting, the JSON viewer renders it as a collapsible tree.

For the rest of the toolkit, including formatting, validating, and converting to CSV, see the roundup of free JSON tools.

Leave a Reply

Your email address will not be published. Required fields are marked *