Tutorial

JSON to XML Conversion: Best Practices

January 20, 2025 JSON Parser Team 10 min read

Introduction

Converting between JSON and XML is a common requirement in modern software development. While both are popular data formats, they have fundamental differences in structure and capabilities. This guide covers best practices for converting JSON to XML while preserving data integrity and handling edge cases.

Understanding the Differences

JSON Structure

{
  "user": {
    "name": "John Doe",
    "age": 30,
    "emails": ["john@example.com", "john.doe@work.com"],
    "active": true
  }
}

Equivalent XML

<?xml version="1.0" encoding="UTF-8"?>
<user>
  <name>John Doe</name>
  <age>30</age>
  <emails>
    <item>john@example.com</item>
    <item>john.doe@work.com</item>
  </emails>
  <active>true</active>
</user>

Key Challenges

1. Arrays Representation

JSON arrays don't map directly to XML. You need to decide on a representation strategy:

Option A: Wrap each item in a generic tag like <item>
Option B: Use singular form of parent tag
Option C: Use attributes to indicate array type

2. Data Types

XML doesn't have native boolean, number, or null types. Everything is text:

// JSON
{"age": 30, "active": true, "middle_name": null}

// XML - all values are strings
<age>30</age>
<active>true</active>
<middle_name></middle_name>

3. Attributes vs Elements

XML supports attributes, JSON doesn't. Choose a convention:

// Using @ prefix for attributes
{
  "user": {
    "@id": "123",
    "name": "John"
  }
}

// Becomes
<user id="123">
  <name>John</name>
</user>

Best Practices

1. Define Clear Naming Conventions

  • Use @ prefix for XML attributes
  • Use $ or _text for text content
  • Use item or singular form for array elements

2. Handle Special Characters

XML requires escaping of special characters:

<     becomes    &lt;
>     becomes    &gt;
&     becomes    &amp;
"     becomes    &quot;
'     becomes    &apos;

3. Preserve Type Information

Use attributes to indicate original JSON types:

<age type="number">30</age>
<active type="boolean">true</active>
<tags type="array">
  <item>developer</item>
  <item>blogger</item>
</tags>

4. Handle Null Values

Multiple approaches for null:

// Option 1: Empty element
<middle_name />

// Option 2: Explicit null attribute
<middle_name xsi:nil="true" />

// Option 3: Omit element entirely

Conversion Algorithms

JavaScript Example

function jsonToXml(obj, rootName = 'root') {
  let xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
  xml += convertNode(obj, rootName);
  return xml;
}

function convertNode(node, nodeName) {
  if (node === null) {
    return `<${nodeName} />`;
  }

  if (typeof node === 'object' && !Array.isArray(node)) {
    let xml = `<${nodeName}>\n`;
    for (let [key, value] of Object.entries(node)) {
      xml += convertNode(value, key) + '\n';
    }
    xml += `</${nodeName}>`;
    return xml;
  }

  if (Array.isArray(node)) {
    let xml = `<${nodeName}>\n`;
    node.forEach(item => {
      xml += convertNode(item, 'item') + '\n';
    });
    xml += `</${nodeName}>`;
    return xml;
  }

  return `<${nodeName}>${escapeXml(String(node))}</${nodeName}>`;
}

function escapeXml(str) {
  return str
    .replace(/&/g, '&amp;')
    .replace(//g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}

Common Pitfalls to Avoid

❌ Don't:
  • Forget to escape special XML characters
  • Use invalid XML tag names (spaces, special chars)
  • Lose array vs object distinction
  • Ignore character encoding issues
  • Convert without documenting your conventions

Validation After Conversion

Always validate your XML output:

  • Use XML validators to ensure well-formed XML
  • Validate against XSD schema if available
  • Test round-trip conversion (JSON → XML → JSON)
  • Verify special characters are properly escaped

Tools and Libraries

JavaScript

  • xml-js - Comprehensive XML/JSON conversion
  • fast-xml-parser - Fast and lightweight
  • Our JSON to XML Converter

Python

  • xmltodict - Bidirectional XML/dict conversion
  • dicttoxml - Dictionary to XML

Java

  • Jackson with XML module
  • JSON-java library

Conclusion

Converting JSON to XML requires careful consideration of structural differences, naming conventions, and data type preservation. By following these best practices and using appropriate tools, you can ensure reliable and consistent conversions.

Try it now!

Convert your JSON to XML using our free online tool: JSON to XML Converter