Online Json Formatter
  • Home
  • JSON Formatter
  • JSON Minify
  • JSON Beautifier
  • Blog
No Result
View All Result
Online Json Formatter
  • Home
  • JSON Formatter
  • JSON Minify
  • JSON Beautifier
  • Blog
No Result
View All Result
Online Json Formatter
No Result
View All Result
json to xml converter

JSON to XML Converter: How to Convert JSON Data to XML Format Online & via Code

Online JSON Formatter by Online JSON Formatter
November 29, 2026
in Online JSON formatter
Reading Time: 14 mins read
0
Share on FacebookShare on Twitter

You’ve got a clean JSON response from an API. But the legacy system you’re integrating with? It only speaks XML.

Sound familiar?

This is one of those everyday developer problems that seems small until you’re elbow-deep in malformed tags and missing namespaces at 11 PM. The good news: converting JSON to XML is straightforward once you understand the structure differences, and there are solid tools and code snippets to do it in minutes.

In this guide, we’ll walk through everything: what JSON to XML conversion actually means, how to do it online for quick tasks, and how to write it yourself in JavaScript, Python, and Node.js.

What Is a JSON to XML Converter?

A JSON to XML converter is exactly what it sounds like: a tool or piece of code that takes data structured in JSON format and transforms it into valid XML format.

Both formats store structured data. Both are human-readable. But their syntax and use cases differ quite a bit.

Here’s a quick side-by-side to make it concrete.

JSON:

{
  "user": {
    "name": "Alex",
    "age": 28,
    "email": "[email protected]"
  }
}

Converted to XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <user>
    <name>Alex</name>
    <age>28</age>
    <email>[email protected]</email>
  </user>
</root>

Same data, different wrapper. The JSON keys become XML element tags, and the values sit inside them.

Before converting your data, you can use our JSON Formatter to organize your JSON structure and make it easier to read.

JSON vs XML: Key Differences You Should Know

Before you convert anything, it helps to understand why these two formats exist and where each one shines.

FeatureJSONXML
SyntaxLightweight, minimalVerbose, tag-based
ReadabilityEasy for developersReadable but wordy
Data typesSupports arrays nativelyNo native array type
AttributesNot supportedSupported
Use casesREST APIs, web appsSOAP APIs, enterprise systems, config files
Parsing speedGenerally fasterSlightly slower

The key thing to remember: JSON was built for the web and APIs. XML was built for document structure and enterprise data exchange. When you’re bridging those two worlds, conversion is unavoidable.

JSON to XML Online Free: Quick Tools for One-Off Conversions

For quick, no-code conversions, online tools are your best friend. No setup, no dependencies—just paste and convert.

Here are some solid options:

  • onlinejsonformatter.com: Simple interface, handles nested objects cleanly.
  • FreeFormatter.com: Includes formatting options and pretty-print output.
  • JSON Formatter & Validator: Validates your JSON before converting (very useful).

These tools work great for:

  • Testing what your converted output should look like.
  • One-off data migrations.
  • Debugging integration issues with XML-based systems.

For anything production or recurring, though, you’ll want to handle this in code.

If your JSON data is difficult to read because of inconsistent spacing or formatting, try our JSON Beautifier to make it more readable before conversion.

JSON to XML Step by Step: Understanding the Conversion Logic

Before jumping into code, let’s nail the conversion rules. This is where most developers hit snags.

Rule 1: Every JSON Object Becomes an XML Element

{ "product": { "id": "101" } }

Converted XML:

<product>
  <id>101</id>
</product>

Rule 2: JSON Arrays Need a Wrapper Element

This is tricky. XML has no native array concept, so each array item needs a tag.

{ "tags": ["python", "api", "xml"] }

Converted XML:

<tags>
  <item>python</item>
  <item>api</item>
  <item>xml</item>
</tags>

Rule 3: JSON Keys Become Tag Names

XML tag names can’t start with numbers or contain spaces. If your JSON keys do, you’ll need to sanitize them before conversion.

Rule 4: The Root Element

XML requires a single root element. JSON objects don’t. Most converters wrap everything in a <root> tag automatically, but in production, you’ll usually want a meaningful root name like <order> or <response>.

JSON to XML in JavaScript

Let’s get into actual code. There’s no native JSON-to-XML method in JavaScript, but you can write a clean recursive function or use a library.

Option 1: Write Your Own Converter

Here’s a lightweight recursive function that handles the most common cases:

function jsonToXml(obj, rootElement = "root") {
  let xml = `<${rootElement}>`;

  for (const key in obj) {
    const value = obj[key];

    if (Array.isArray(value)) {
      value.forEach(item => {
        xml += `<${key}>${typeof item === "object" ? jsonToXml(item, "").slice(6, -7) : item}</${key}>`;
      });
    } else if (typeof value === "object" && value !== null) {
      xml += jsonToXml(value, key);
    } else {
      xml += `<${key}>${value}</${key}>`;
    }
  }

  xml += `</${rootElement}>`;
  return xml;
}

// Usage
const data = {
  order: {
    id: "ORD-001",
    customer: "Jane Doe",
    items: ["laptop", "mouse", "keyboard"]
  }
};

const xmlOutput = jsonToXml(data);
console.log(xmlOutput);

What this does: It recursively walks through the JSON object. For each key, it checks if the value is an array, a nested object, or a primitive and wraps it in XML tags accordingly.

Option 2: Use the xml-js Library

For production use, xml-js is the go-to npm package. It handles edge cases much better than a hand-rolled function.

Install the package:

npm install xml-js

Conversion code:

const convert = require("xml-js");

const jsonData = JSON.stringify({
  order: {
    id: "ORD-001",
    customer: "Jane Doe",
    status: "shipped"
  }
});

const xmlResult = convert.json2xml(jsonData, {
  compact: true,
  ignoreComment: true,
  spaces: 2
});

console.log(xmlResult);

Output:

<order>
  <id>ORD-001</id>
  <customer>Jane Doe</customer>
  <status>shipped</status>
</order>

The compact: true option keeps the output clean. The spaces: 2 option adds indentation for readability.

JSON to XML in Node.js

Node.js conversion follows the same approach as JavaScript—you’re using the same xml-js or similar libraries.

But here’s a practical example of a complete Node.js module you can drop into a project:

File: json-to-xml.js

const convert = require("xml-js");
const fs = require("fs");

function convertFile(inputPath, outputPath) {
  try {
    const rawJson = fs.readFileSync(inputPath, "utf8");

    const xmlOutput = convert.json2xml(rawJson, {
      compact: true,
      ignoreComment: true,
      spaces: 2
    });

    fs.writeFileSync(
      outputPath,
      `<?xml version="1.0" encoding="UTF-8"?>\n${xmlOutput}`
    );

    console.log(`✅ Converted successfully: ${outputPath}`);
  } catch (err) {
    console.error("Conversion failed:", err.message);
  }
}

// Run it
convertFile("./data/input.json", "./output/result.xml");

What this does:

  1. Reads a JSON file from disk.
  2. Converts it to XML.
  3. Prepends the XML declaration header.
  4. Writes the output to an XML file.

Simple, reusable, and easy to wire into any pipeline.

JSON to XML in Python

Python’s ecosystem makes this even cleaner. The dicttoxml library is a popular option.

Install the package:

pip install dicttoxml

Conversion code:

import jsonimport dicttoxmlfrom xml.dom.minidom import parseString# Load JSON datawith open("data.json", "r") as f:    data = json.load(f)# Convert to XMLxml_bytes = dicttoxml.dicttoxml(    data,    custom_root="response",    attr_type=False)# Pretty printdom = parseString(xml_bytes)pretty_xml = dom.toprettyxml(indent="  ")print(pretty_xml)

Output for {"user": {"name": "Alex", "role": "admin"}}:

<?xml version="1.0" ?>
<response>
  <user>
    <name>Alex</name>
    <role>admin</role>
  </user>
</response>

The attr_type=False option removes the auto-generated type attributes that dicttoxml adds by default. Most of the time, you don’t want those.

Handling Arrays in Python

import jsonimport dicttoxmldata = {    "products": ["laptop", "tablet", "phone"]}xml_output = dicttoxml.dicttoxml(    data,    custom_root="catalog",    attr_type=False)print(xml_output.decode())

Output:

<catalog>
  <products>
    <item>laptop</item>
    <item>tablet</item>
    <item>phone</item>
  </products>
</catalog>

Each array element gets wrapped in an <item> tag. If you need custom tag names per element, you can pass an item_func to dicttoxml.

Building a JSON to XML API

Need a REST endpoint that accepts JSON and returns XML? Here’s a minimal Express.js setup:

const express = require("express");
const convert = require("xml-js");

const app = express();

app.use(express.json());

app.post("/convert/json-to-xml", (req, res) => {
  try {
    const jsonInput = JSON.stringify(req.body);

    const xmlOutput = convert.json2xml(jsonInput, {
      compact: true,
      spaces: 2
    });

    res.set("Content-Type", "application/xml");

    res.send(
      `<?xml version="1.0" encoding="UTF-8"?>\n${xmlOutput}`
    );
  } catch (err) {
    res.status(400).json({
      error: "Invalid JSON input"
    });
  }
});

app.listen(3000, () => {
  console.log("Converter API running on port 3000");
});

POST any JSON body to /convert/json-to-xml and you’ll get back clean XML. Useful for microservices that act as format bridges between systems.

JSON to XML Example: Real-World Use Cases

Let’s look at where you’ll actually need this in production.

1. SOAP API Integration

SOAP services common in banking, healthcare, and enterprise software require XML payloads. If your backend produces JSON, you’ll need to convert it before sending.

2. Configuration File Migration

Some deployment systems use XML configs (Maven, Android manifests, Spring). If you’re generating configs programmatically from a JSON source of truth, conversion is built into the pipeline.

3. Document Generation

Systems like DITA or DocBook use XML for structured documents. If your content lives in JSON (from a CMS or database), you convert it before publishing.

4. EDI and B2B Data Exchange

Electronic Data Interchange used in logistics, supply chains, and retail often works in XML. Automated order management systems convert JSON from internal APIs to XML for partner systems.

Common Mistakes to Avoid

Here’s where things go sideways most often.

1. Not Adding an XML Declaration

Always prepend:

<?xml version="1.0" encoding="UTF-8"?>

Some parsers will reject XML without it.

2. Invalid XML Tag Names from JSON Keys

JSON keys like "1st-item" or "total amount" will break XML. Sanitize your keys before conversion:

function sanitizeKey(key) {
  return key
    .replace(/[^a-zA-Z0-9_.-]/g, "_")
    .replace(/^[^a-zA-Z_]/, "_$&");
}

3. Ignoring Character Encoding

XML is strict about special characters. Always encode &, <, >, ", and ' as their XML entities (&amp;, &lt;, etc.). Good libraries handle this automatically.

4. Losing Data Types

XML doesn’t have native types. true, 42, and "42" will all look the same in XML. If you need to preserve types, add xsi:type attributes or use a schema.

5. Forgetting Namespaces for SOAP

If you’re converting for a SOAP endpoint, the XML likely needs specific namespace declarations. Pure converters won’t add these—you’ll need to handle them manually or with a template.

Best Practices for JSON to XML Conversion

A few things that save you headaches in production:

  • Validate your JSON first before converting. Use our JSON Validator to catch syntax errors and invalid JSON structures early.
  • Define your root element explicitly rather than relying on a default <root> tag.
  • Test with your target system. What’s technically valid XML may still fail against a specific schema or DTD.
  • Version your schema if the converted XML is consumed by multiple systems. Changes can break downstream systems.
  • Log conversion errors separately from application errors. Format failures are a different category of problem.

If you need to inspect or understand the structure of your JSON before converting it, an online JSON Parser can also help.

Tools Worth Bookmarking

Beyond online converters, here are some developer tools that make working with JSON and XML easier day-to-day:

  • JSON Formatter & Validator: Validate and format before you convert.
  • XML Validator: Check your output is well-formed.
  • xml-js (npm): A JavaScript/Node.js option for JSON-to-XML conversion.
  • dicttoxml (pip): A Python option with array handling.
  • Postman: Great for testing JSON-to-XML API endpoints directly.

Conclusion

Converting JSON to XML isn’t complicated, but doing it correctly in production requires understanding how arrays map to elements, how to handle special characters, and what your target system actually expects.

For quick tasks, any of the free online converters will get you there in seconds. For code-level conversion, xml-js in Node.js and dicttoxml in Python are both solid options. And if you’re bridging systems at scale, wrapping the logic in a small API service keeps things clean and reusable.

Next time you hit that “XML only” integration requirement, you’ll know exactly what to reach for.

Tags: JSONConverterJSONtoXMLOnlineJSONFormatterWebDevelopmentXMLConverter
Previous Post

PHP json_decode() Function: How to Decode JSON in PHP with Examples & Online Tool

Online JSON Formatter

Our Online JSON Formatter is a free and powerful tool to format, validate, save, and share JSON data with ease. It includes features like converting JSON to XML, CSV, or YAML, along with a live editor, tree viewer, and built-in validator.
  • Privacy Policy
  • About Us
  • FAQ
  • Blog
  • Contact Us
  • DMCA Policy
  • Disclaimer

Copyright © Online JSON Formatter 2025 v1.3   DMCA.com Protection Status

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
No Result
View All Result
  • Home
  • JSON Formatter
  • JSON Minify
  • JSON Beautifier
  • Blog

Copyright © Online JSON Formatter 2025 v1.3   DMCA.com Protection Status