jsondecode.com logo

HomeChevronBlogChevronJSON to XML Conversion: Complete Guide

Blog post

JSON to XML Conversion: Complete Guide

Convert JSON to XML in JavaScript, Python, and online tools. Understand the structural differences and handle edge cases.

author

Shashank Jain

Author

14/06/20261 minute 40 seconds read
JSON to XML Conversion: Complete GuideJSON to XML Conversion: Complete Guide

Article

JSON vs XML Structure

JSON and XML both represent structured data but with different philosophies. JSON uses key-value pairs and arrays. XML uses elements, attributes, and text nodes. Converting between them requires mapping these concepts.

JSON to XML in JavaScript

// Using xml-js library
const xmljs = require('xml-js');

const json = { person: { name: 'Alice', age: 30, hobbies: { hobby: ['reading', 'coding'] } } };

const xml = xmljs.js2xml(json, { compact: true, spaces: 2 });
console.log(xml);
// <person>
//   <name>Alice</name>
//   <age>30</age>
//   <hobbies>
//     <hobby>reading</hobby>
//     <hobby>coding</hobby>
//   </hobbies>
// </person>

JSON to XML in Python

import json
import xml.etree.ElementTree as ET

def json_to_xml(data, root_tag='root'):
    root = ET.Element(root_tag)
    _build_xml(root, data)
    return ET.tostring(root, encoding='unicode', xml_declaration=False)

def _build_xml(parent, data):
    if isinstance(data, dict):
        for key, val in data.items():
            child = ET.SubElement(parent, key)
            _build_xml(child, val)
    elif isinstance(data, list):
        for item in data:
            child = ET.SubElement(parent, 'item')
            _build_xml(child, item)
    else:
        parent.text = str(data)

data = {'name': 'Alice', 'age': 30}
print(json_to_xml(data, 'person'))
# <person><name>Alice</name><age>30</age></person>

Key Mapping Challenges

JSON ConceptXML EquivalentIssue
Object keyElement tagXML tags cannot start with numbers
ArrayRepeated elementsNeed a wrapper element or naming convention
nullEmpty element or xsi:nilNo universal standard
BooleanText true/falseNo native boolean type in XML
NumberText contentNo native number type in XML

Using xmltodict in Python

import xmltodict
import json

# XML to JSON
xml = '<person><name>Alice</name><age>30</age></person>'
data = xmltodict.parse(xml)
print(json.dumps(data, indent=2))

# JSON to XML
data = {'person': {'name': 'Alice', 'age': '30'}}
xml = xmltodict.unparse(data, pretty=True)
print(xml)

FAQ

Is JSON replacing XML?

For REST APIs and web applications, yes — JSON has largely replaced XML. XML remains dominant in enterprise systems, SOAP APIs, document formats (DOCX, SVG, HTML), and configuration systems like Maven and Spring.

Can all JSON be converted to XML?

Yes, but with caveats. XML tag names cannot start with numbers or contain spaces, so JSON keys like '1st' or 'my key' need sanitizing. JSON arrays require a naming convention for the repeated XML elements.

What library should I use for JSON to XML in Node.js?

xml-js is the most popular. fast-xml-parser is faster for large documents. For simple cases, you can build a recursive function without any library.

Does jsondecode.com support JSON to XML conversion?

Yes, use the JSON to XML tool in the tools section.

How do I handle XML attributes in JSON?

xml-js uses a convention where @ prefix on JSON keys maps to XML attributes: { '@id': '1', '#text': 'Alice' } becomes <element id='1'>Alice</element>.

Keep reading

Recent blogs

View all

If jsondecode.com saved you time, share it with your team

Free forever. No ads. No sign-up. Help other developers find it.