← Back to XML Articles

JSON to XML Conversion Guide

Complete guide to converting JSON data to XML format with tools, code examples, and best practices

Conversion12 min read

Converting JSON to XML is a common task when integrating systems that use different data formats. While JSON is the modern standard for web APIs, many enterprise systems, legacy applications, and specific industries still rely on XML.

This guide covers everything you need to know about converting JSON to XML, from simple online tools to programming solutions in multiple languages.

Quick Start: Convert JSON to XML Now

Fastest Method: Use Our Free Tool

The quickest way to convert JSON to XML:

  1. 1.Go to our JSON to XML Converter
  2. 2.Paste your JSON data or upload file
  3. 3.Click "Convert" - instant results
  4. 4.Download XML file or copy to clipboard
Convert JSON to XML Now →

Why Convert JSON to XML?

Enterprise Integration

Many enterprise systems (SAP, Oracle, legacy apps) require XML. Convert JSON from modern APIs to XML for these systems.

SOAP Services

SOAP web services use XML exclusively. Convert JSON data to XML for SOAP API requests.

Configuration Files

Some applications require XML config files. Convert JSON configs to XML format.

Data Migration

Migrate data between systems that use different formats. JSON to XML conversion enables smooth transitions.

JSON vs XML: Side-by-Side

Here's how the same data looks in both formats:

JSON (Source):

JSON
{
  "user": {
    "id": 123,
    "name": "John Doe",
    "email": "[email protected]",
    "active": true,
    "roles": ["admin", "editor"],
    "address": {
      "street": "123 Main St",
      "city": "New York",
      "zip": "10001"
    }
  }
}

XML (Result):

XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <user>
    <id>123</id>
    <name>John Doe</name>
    <email>[email protected]</email>
    <active>true</active>
    <roles>admin</roles>
    <roles>editor</roles>
    <address>
      <street>123 Main St</street>
      <city>New York</city>
      <zip>10001</zip>
    </address>
  </user>
</root>

Key Differences:

JSON:

  • • Curly braces {}
  • • Native arrays []
  • • Key-value pairs
  • • Data types (number, boolean)
  • • More compact

XML:

  • • Opening/closing tags
  • • Repeated elements for arrays
  • • Hierarchical structure
  • • Everything is text
  • • More verbose

Using Online Conversion Tools

Our free JSON to XML converter offers:

  • Instant conversion - Results in seconds
  • No registration - Use immediately
  • Free forever - No limits or costs
  • Privacy-focused - Browser-based processing
  • Format options - Customize XML output

Code Examples

Python

Python
import json
import xml.etree.ElementTree as ET

def json_to_xml(json_obj, root_name='root'):
    """Convert JSON to XML"""
    
    def build_xml(parent, data):
        if isinstance(data, dict):
            for key, value in data.items():
                if isinstance(value, list):
                    for item in value:
                        child = ET.SubElement(parent, key)
                        if isinstance(item, (dict, list)):
                            build_xml(child, item)
                        else:
                            child.text = str(item)
                else:
                    child = ET.SubElement(parent, key)
                    build_xml(child, value)
        elif isinstance(data, list):
            for item in data:
                build_xml(parent, item)
        else:
            parent.text = str(data)
    
    root = ET.Element(root_name)
    build_xml(root, json_obj)
    return ET.ElementTree(root)

# Example usage
json_data = {
    "user": {
        "id": 123,
        "name": "John Doe",
        "email": "[email protected]"
    }
}

tree = json_to_xml(json_data)
ET.indent(tree, space="    ")
tree.write('output.xml', encoding='utf-8', xml_declaration=True)
print("Converted successfully!")

JavaScript/Node.js

JavaScript
// Install: npm install xml2js
const xml2js = require('xml2js');

const jsonData = {
  user: {
    id: 123,
    name: 'John Doe',
    email: '[email protected]',
    roles: ['admin', 'editor']
  }
};

// Convert JSON to XML
const builder = new xml2js.Builder({
  rootName: 'root',
  xmldec: { version: '1.0', encoding: 'UTF-8' }
});

const xml = builder.buildObject(jsonData);
console.log(xml);

// Save to file
const fs = require('fs');
fs.writeFileSync('output.xml', xml);

PHP

PHP
<?php
function jsonToXml($data, $rootElement = 'root', $xml = null) {
    if ($xml === null) {
        $xml = new SimpleXMLElement("<{$rootElement}/>");
    }
    
    foreach ($data as $key => $value) {
        $key = is_numeric($key) ? "item$key" : $key;
        
        if (is_array($value)) {
            $subnode = $xml->addChild($key);
            jsonToXml($value, $key, $subnode);
        } else {
            $xml->addChild($key, htmlspecialchars($value));
        }
    }
    
    return $xml;
}

// Example usage
$jsonData = [
    'user' => [
        'id' => 123,
        'name' => 'John Doe',
        'email' => '[email protected]'
    ]
];

$xml = jsonToXml($jsonData);
$dom = dom_import_simplexml($xml)->ownerDocument;
$dom->formatOutput = true;
$xmlString = $dom->saveXML();

file_put_contents('output.xml', $xmlString);
echo "Converted successfully!";
?>

Common Challenges & Solutions

❌ Challenge: Arrays in JSON

Issue: JSON arrays ["a", "b"] become repeated XML elements

Solution: Each array item becomes a separate XML element with the same tag name.

❌ Challenge: Data Types Lost

Issue: XML doesn't have native types (numbers, booleans become strings)

Solution: Use attributes or schema to preserve type information if needed.

❌ Challenge: Special Characters

Issue: Characters like < > & must be escaped in XML

Solution: Use proper XML encoding/escaping in your conversion library.

❌ Challenge: Numeric Keys

Issue: XML tags can't start with numbers

Solution: Prefix numeric keys (e.g., item1).

❌ Challenge: Root Element Required

Issue: XML requires exactly one root element

Solution: Wrap JSON data in a root element like <root>.

Best Practices

Validate JSON First

Use a JSON validator to ensure your JSON is valid before converting.

Choose Meaningful Root Name

Use a descriptive root element name instead of generic "root" or "data".

Handle Arrays Consistently

Decide on array handling strategy and apply consistently throughout.

Pretty Print XML

Format XML with indentation for readability. Use our XML formatter.

Test Round-Trip Conversion

Convert JSON→XML→JSON to verify data integrity is preserved.

Document Conversion Rules

If converting regularly, document how arrays, nulls, and special cases are handled.

Additional Resources

Conversion Tools:

External Resources:

Related Articles