XML to JSON Tutorial: Convert XML to JSON with Examples

Converting XML to JSON is a common task when migrating from legacy SOAP APIs to modern REST APIs, or when a third-party feed delivers XML but your application expects JSON. This guide explains the conversion rules with concrete examples.

Quick start: use the online converter

Paste any XML into the XML to JSON converter to get formatted JSON instantly, without writing any code.

How XML elements map to JSON keys

Each XML element becomes a JSON key. The element's text content becomes the value. The root element is typically used as the top-level JSON object key.

<!-- XML -->
<person>
  <name>Alice</name>
  <age>30</age>
  <active>true</active>
</person>
// JSON
{
  "name": "Alice",
  "age": 30,
  "active": true
}

Note: numbers and booleans in text content are cast to their native JSON types when the converter can infer them unambiguously.

How repeated XML elements become JSON arrays

When multiple sibling elements share the same tag name, they are grouped into a JSON array. This is the main structural difference between XML and JSON.

<!-- XML -->
<bookstore>
  <book>
    <title>Learning XML</title>
    <price>39.95</price>
  </book>
  <book>
    <title>JSON at Work</title>
    <price>49.99</price>
  </book>
</bookstore>
// JSON
{
  "book": [
    { "title": "Learning XML", "price": 39.95 },
    { "title": "JSON at Work", "price": 49.99 }
  ]
}

How empty XML elements map to JSON null

Self-closing tags and elements with no content map to null in JSON.

<!-- XML -->
<user>
  <name>Bob</name>
  <middleName/>
</user>
// JSON
{
  "name": "Bob",
  "middleName": null
}

Nested XML elements

Nested elements become nested JSON objects:

<!-- XML -->
<order>
  <customer>
    <name>Alice</name>
    <email>alice@example.com</email>
  </customer>
  <total>199.99</total>
</order>
// JSON
{
  "customer": {
    "name": "Alice",
    "email": "alice@example.com"
  },
  "total": 199.99
}

Convert XML to JSON in JavaScript

In the browser you can parse XML with the built-in DOMParser and walk the DOM recursively:

function xmlToJson(node) {
  const children = Array.from(node.children)

  // No child elements — return text content
  if (children.length === 0) {
    const text = node.textContent?.trim() ?? ''
    if (text === '') return null
    if (text === 'true') return true
    if (text === 'false') return false
    const num = Number(text)
    if (!isNaN(num)) return num
    return text
  }

  const obj = {}
  for (const child of children) {
    const key = child.tagName
    const val = xmlToJson(child)
    if (key in obj) {
      if (!Array.isArray(obj[key])) obj[key] = [obj[key]]
      obj[key].push(val)
    } else {
      obj[key] = val
    }
  }
  return obj
}

const parser = new DOMParser()
const doc = parser.parseFromString(xmlString, 'text/xml')
const json = xmlToJson(doc.documentElement)
console.log(JSON.stringify(json, null, 2))

Convert XML to JSON in Python

import xml.etree.ElementTree as ET
import json

def xml_to_dict(element):
    children = list(element)
    if not children:
        text = (element.text or '').strip()
        if text == '': return None
        if text.lower() == 'true': return True
        if text.lower() == 'false': return False
        try: return int(text)
        except ValueError: pass
        try: return float(text)
        except ValueError: pass
        return text

    result = {}
    for child in children:
        val = xml_to_dict(child)
        if child.tag in result:
            if not isinstance(result[child.tag], list):
                result[child.tag] = [result[child.tag]]
            result[child.tag].append(val)
        else:
            result[child.tag] = val
    return result

root = ET.fromstring(xml_string)
data = xml_to_dict(root)
print(json.dumps(data, indent=2))

Common pitfalls

  • XML attributes are lost — simple converters only handle element content, not attributes. If your XML uses attributes heavily, you may need a custom mapping.
  • Mixed content — XML elements with both text and child elements (common in HTML-like XML) don't map cleanly to JSON.
  • Namespaces — XML namespaces (xmlns: prefixes) are usually included verbatim in the JSON key names, which can be noisy.

Convert XML to JSON online

Use the XML to JSON converter to transform any XML document instantly. For the reverse, use the JSON to XML converter.