正在加载,请稍候…

JSON vs XML: When and How to Convert Between Formats

A practical guide comparing JSON and XML for data conversion. Learn key differences, when to use each, common pitfalls, and a full end-to-end conversion

server racks with network cables

When working with data exchange between systems, you'll often encounter two dominant formats: JSON (JavaScript Object Notation) and XML (eXtensible Markup Language). While JSON has become the default for modern REST APIs, XML remains essential in enterprise environments, configuration files (like Maven's pom.xml), Android layouts, SOAP web services, and document formats (Office Open XML, SVG).

This article dives deep into the practical aspects of converting between JSON and XML: when to choose one over the other, how to handle structural differences, and a complete worked example. If you need a quick conversion, try our JSON to XML converter.

Key Differences Between JSON and XML

Feature JSON XML
Syntax Key-value pairs, arrays Tag-based markup with attributes
Data types Native: string, number, boolean, null, array, object All values are strings; types enforced via XSD
Comments Not supported (JSON5/JSONC add them) Supported natively
Validation No built-in schema (JSON Schema external) DTD, XML Schema (XSD)
Parsing speed Faster (less verbose) Slower (more verbose)
File size Smaller Larger (redundant tags)
Namespace Not supported Supported via xmlns
Attributes Not supported (use nested objects) Supported on elements

When to Use JSON vs XML

Use JSON when:

  • Building RESTful APIs or microservices
  • Exchanging data with JavaScript frontends
  • Handling lightweight, fast data transfer
  • Working with mobile apps or IoT devices

Use XML when:

  • Integrating with enterprise systems (SOAP, legacy APIs)
  • Creating configuration files (Spring, Maven, Android)
  • Representing documents with mixed content (e.g., XHTML, DocBook)
  • Needing schema validation and namespace support
  • Working with RSS feeds or SVG graphics

Structural Mapping Between JSON and XML

Converting between the two requires understanding how each structure maps:

JSON XML
Object {} Root element with child elements
Array [] Repeated element (or wrapper element)
String "value" Element text content
Number 42 Element text content (string)
Boolean true Element text content ("true" / "false")
null Empty element or omitted
Nested object Nested elements
No attribute concept Attribute on element

Common Pitfalls in Conversion

  • Arrays with single element: JSON [42] may become <item>42</item> (no wrapper). Ensure your converter always produces an array wrapper for consistency.
  • Attributes vs. child elements: JSON has no native attributes. Converters often use a special convention (e.g., @attr or _attributes). Decide upfront.
  • Namespace handling: XML namespaces (xmlns:prefix) have no JSON equivalent. Strip or encode them.
  • Mixed content: XML allows text + child elements (e.g., <p>Hello <b>world</b></p>). JSON requires a structured representation.
  • Comments: XML comments are lost in JSON. If needed, store them as a special key.

End-to-End Conversion Example

Suppose we have a JSON object representing a library catalog and want to convert it to XML.

Input JSON:

{
  "library": {
    "name": "City Library",
    "books": [
      {
        "id": "001",
        "title": "Java Fundamentals",
        "author": "Alice",
        "price": 45.00,
        "available": true
      },
      {
        "id": "002",
        "title": "Python Data Science",
        "author": "Bob",
        "price": 55.00,
        "available": false
      }
    ]
  }
}

Target XML:

<?xml version="1.0" encoding="UTF-8"?>
<library>
  <name>City Library</name>
  <books>
    <book id="001">
      <title>Java Fundamentals</title>
      <author>Alice</author>
      <price>45.00</price>
      <available>true</available>
    </book>
    <book id="002">
      <title>Python Data Science</title>
      <author>Bob</author>
      <price>55.00</price>
      <available>false</available>
    </book>
  </books>
</library>

Conversion Rules Applied

  1. The root JSON object library becomes the root XML element <library>.
  2. Each key-value pair becomes a child element. The key is the element name, the value is the text content.
  3. The array books is represented by a wrapper element <books> containing repeated <book> elements.
  4. The id field is promoted to an XML attribute (by convention).
  5. Numbers and booleans become text strings.

Using a Converter (Pseudocode)

import json
import xml.etree.ElementTree as ET

def json_to_xml(json_obj, root_name="root"):
    root = ET.Element(root_name)
    _build_xml(root, json_obj)
    return ET.tostring(root, encoding="unicode")

def _build_xml(parent, data):
    if isinstance(data, dict):
        for key, value in data.items():
            # Special handling for attributes: keys starting with '@'
            if key.startswith('@'):
                parent.set(key[1:], str(value))
            elif key == '#text':
                parent.text = str(value)
            else:
                child = ET.SubElement(parent, key)
                _build_xml(child, value)
    elif isinstance(data, list):
        for item in data:
            # Use parent's tag for each list item (singularize if needed)
            item_elem = ET.SubElement(parent, parent.tag.rstrip('s'))
            _build_xml(item_elem, item)
    else:
        parent.text = str(data)

# Usage:
json_input = '{"library": {"name": "City Library", ...}}'
xml_output = json_to_xml(json.loads(json_input), "library")
print(xml_output)

Security and Performance Considerations

  • XML External Entity (XXE) attacks: When parsing XML, disable external entity resolution to prevent file disclosure or SSRF. In Python's xml.etree.ElementTree, use defusedxml.
  • Billion Laughs attack: Malicious XML with nested entity expansions can cause denial of service. Limit entity expansion depth.
  • JSON parsing: Generally safer, but watch for prototype pollution in JavaScript environments.
  • Large payloads: XML is more verbose; for bulk data, JSON reduces bandwidth. Use streaming parsers (e.g., SAX for XML, ijson for JSON) for huge files.

FAQ

Why does my converted XML have no attributes?

JSON has no built-in attribute concept. Most converters treat all fields as child elements. To get attributes, you must use a convention (e.g., prefix keys with @ or use a nested _attributes object). Check your converter's documentation.

Can I preserve comments during conversion?

Standard JSON does not support comments. If you need comments, consider using JSON5 or storing them as a special key (e.g., "_comment"). XML comments are typically lost when converting to JSON.

How do I handle XML namespaces in JSON?

Namespaces can be represented as JSON keys with the full namespace URI (e.g., "xmlns:prefix": "http://example.com/ns") or by encoding the prefix in the element name (e.g., "prefix:element"). Choose a consistent strategy.

What is the best tool for JSON to XML conversion?

For one-off conversions, our JSON to XML converter works well. For programmatic use, libraries like xmltodict (Python) or json2xml (Node.js) are popular.

Is XML still relevant in 2025?

Yes. While JSON dominates web APIs, XML is irreplaceable in enterprise integration (SOAP), configuration (Maven, Android), document formats (DOCX, XLSX), and standards like SVG and RSS. Understanding both is essential for any developer.