XML to JSON

Convert XML to JSON format

Try an example

XML Input

JSON Output

Runs locally · Safe to paste secrets
JSON will appear here…

What is XML to JSON Conversion?

XML to JSON conversion is the process of transforming data from Extensible Markup Language (XML) into JavaScript Object Notation (JSON). Both formats represent structured, hierarchical data, but they use different syntax and data models. XML uses opening and closing tags with optional attributes, while JSON uses key-value pairs, arrays, and primitive types. Converting XML to JSON lets you work with XML data in environments where JSON is the native format, such as JavaScript runtimes, REST APIs, and NoSQL databases.

The conversion is not always one-to-one. XML has constructs with no direct JSON equivalent: attributes, mixed content (text interleaved with child elements), processing instructions, comments, CDATA sections, and namespace declarations. Different conversion libraries handle these constructs differently, which is why multiple conventions exist. The most common approach prefixes attribute names with @ and places text content in a #text field when attributes are present on the same element.

XML to JSON conversion is a common step when migrating from SOAP to REST, consuming legacy enterprise APIs, or processing government and financial data feeds that mandate XML. Rather than rewriting producers and consumers simultaneously, teams convert the XML payload at the boundary layer and pass JSON downstream. AWS API Gateway, Apache Camel, and MuleSoft all support this pattern natively.

XML input
<bookstore>
  <book category="fiction">
    <title lang="en">The Great Gatsby</title>
    <author>F. Scott Fitzgerald</author>
    <year>1925</year>
    <price>10.99</price>
  </book>
  <book category="non-fiction">
    <title lang="en">Sapiens</title>
    <author>Yuval Noah Harari</author>
    <year>2011</year>
    <price>14.99</price>
  </book>
</bookstore>
JSON output
{
  "bookstore": {
    "book": [
      {
        "@category": "fiction",
        "title": {
          "@lang": "en",
          "#text": "The Great Gatsby"
        },
        "author": "F. Scott Fitzgerald",
        "year": "1925",
        "price": "10.99"
      },
      {
        "@category": "non-fiction",
        "title": {
          "@lang": "en",
          "#text": "Sapiens"
        },
        "author": "Yuval Noah Harari",
        "year": "2011",
        "price": "14.99"
      }
    ]
  }
}

Why Use an Online XML to JSON Converter?

Writing a one-off conversion script takes time, especially when the XML contains attributes, namespaces, or repeated elements that need to become JSON arrays. A browser-based converter gives you the JSON output in seconds so you can inspect the structure and move on.

Instant conversion
Paste XML and get JSON output immediately. No need to install a library, write a script, or configure a build tool.
🔒
Privacy-first processing
The entire conversion runs in your browser using JavaScript. Your XML data never leaves your machine and is never uploaded to any server.
🔀
Handles attributes and arrays
Attributes are mapped to @-prefixed keys. Repeated sibling elements are grouped into JSON arrays automatically, following the Parker or BadgerFish convention.
📋
No account required
Open the page, paste your XML, and copy the JSON result. No sign-up, no API key, no usage limits.

XML to JSON Use Cases

Frontend development
Convert XML API responses into JSON so you can render data in React, Vue, or Angular components without adding an XML parsing library to your client bundle.
Backend engineering
Transform SOAP payloads, RSS/Atom feeds, or XML-RPC responses into JSON at the API gateway layer before passing data to microservices that expect JSON input.
DevOps and CI/CD
Convert XML test reports (JUnit, NUnit, xUnit) into JSON for ingestion by dashboards, Slack bots, or custom CI notification pipelines.
QA and testing
Compare converted JSON snapshots against expected output to verify that an XML-producing service has not changed its response structure between releases.
Data engineering
Convert XML exports from government portals, financial feeds (FIX, FIXML), or healthcare systems (HL7 CDA) into JSON for loading into BigQuery, Snowflake, or Elasticsearch.
Learning data formats
Students studying data interchange can paste XML samples into the converter to see exactly how elements, attributes, and nesting map to JSON keys, objects, and arrays.

XML to JSON Mapping Reference

XML and JSON have different data models. The table below shows how each XML construct maps to its JSON equivalent under the most common convention (@ for attributes, #text for text alongside attributes). Some constructs, like mixed content and comments, have no standard JSON representation.

XML ConstructXML ExampleJSON Equivalent
Element<name>text</name>"name": "text"
Nested elements<a><b>1</b></a>"a": { "b": "1" }
Attributes<el attr="v"/>"el": { "@attr": "v" }
Text + attributes<el a="1">text</el>"el": { "@a": "1", "#text": "text" }
Repeated elements<r><i>1</i><i>2</i></r>"r": { "i": ["1", "2"] }
Mixed content<p>A <b>B</b> C</p>Varies by convention
CDATA<![CDATA[raw]]>"#cdata": "raw" or flattened
Namespacesxmlns:prefix="uri"Prefix preserved or stripped
Empty element<el/>"el": null or ""
Comments<!-- note -->Discarded (no JSON equivalent)

XML to JSON Conventions Compared

No single standard governs how XML maps to JSON. Three conventions are widely used, each with different trade-offs for attribute handling, array detection, and text preservation.

BadgerFish
Every text node goes into a $ key. Attributes get @-prefixed keys. Namespaces are preserved as @xmlns entries. Verbose but lossless: you can round-trip back to XML without losing data.
Parker
Strips attributes entirely and converts text-only elements to bare values. Repeated elements become arrays. Compact and clean, but destructive: attributes and namespace info are discarded.
GData (Google Data)
Uses $t for text content and preserves attributes as top-level keys without a prefix. A middle ground between BadgerFish verbosity and Parker simplicity. Used historically in Google APIs.

Code Examples

Below are working examples for converting XML to JSON in JavaScript, Python, Go, and the command line. Each example handles nested elements and repeated sibling tags.

JavaScript (browser)
// Using the DOMParser API to walk XML and build a JSON object
function xmlToJson(xml) {
  const parser = new DOMParser()
  const doc = parser.parseFromString(xml, 'application/xml')

  function nodeToObj(node) {
    const obj = {}
    // Handle attributes
    if (node.attributes) {
      for (const attr of node.attributes) {
        obj['@' + attr.name] = attr.value
      }
    }
    // Handle child nodes
    for (const child of node.childNodes) {
      if (child.nodeType === 3) { // text
        const text = child.textContent.trim()
        if (text) obj['#text'] = text
      } else if (child.nodeType === 1) { // element
        const key = child.nodeName
        const val = nodeToObj(child)
        if (obj[key]) {
          if (!Array.isArray(obj[key])) obj[key] = [obj[key]]
          obj[key].push(val)
        } else {
          obj[key] = val
        }
      }
    }
    // Simplify text-only nodes
    const keys = Object.keys(obj)
    if (keys.length === 1 && keys[0] === '#text') return obj['#text']
    return obj
  }

  return nodeToObj(doc.documentElement)
}

const xml = '<user><name>Alice</name><role>admin</role></user>'
console.log(JSON.stringify(xmlToJson(xml), null, 2))
// → { "name": "Alice", "role": "admin" }
Python
import xmltodict
import json

xml = """
<user>
  <name>Alice</name>
  <roles>
    <role>admin</role>
    <role>editor</role>
  </roles>
</user>
"""

# xmltodict converts XML to an OrderedDict
result = xmltodict.parse(xml)
print(json.dumps(result, indent=2))
# → {
# →   "user": {
# →     "name": "Alice",
# →     "roles": { "role": ["admin", "editor"] }
# →   }
# → }

# With the standard library (xml.etree.ElementTree)
import xml.etree.ElementTree as ET

def etree_to_dict(elem):
    d = {}
    if elem.attrib:
        d.update({f"@{k}": v for k, v in elem.attrib.items()})
    for child in elem:
        child_data = etree_to_dict(child)
        if child.tag in d:
            if not isinstance(d[child.tag], list):
                d[child.tag] = [d[child.tag]]
            d[child.tag].append(child_data)
        else:
            d[child.tag] = child_data
    if elem.text and elem.text.strip():
        if d:
            d["#text"] = elem.text.strip()
        else:
            return elem.text.strip()
    return d

root = ET.fromstring(xml)
print(json.dumps(etree_to_dict(root), indent=2))
Go
package main

import (
    "encoding/json"
    "encoding/xml"
    "fmt"
    "strings"
)

// For simple, known schemas — define a struct
type User struct {
    XMLName xml.Name `xml:"user"`
    Name    string   `xml:"name"`
    Roles   []string `xml:"roles>role"`
}

func main() {
    data := `<user><name>Alice</name><roles><role>admin</role><role>editor</role></roles></user>`
    var user User
    xml.NewDecoder(strings.NewReader(data)).Decode(&user)

    out, _ := json.MarshalIndent(user, "", "  ")
    fmt.Println(string(out))
    // → { "Name": "Alice", "Roles": ["admin", "editor"] }
}
CLI (xmllint + jq / yq)
# Using xq (part of yq, a jq wrapper for XML)
# Install: pip install yq  OR  brew install yq
echo '<user><name>Alice</name></user>' | xq .
# → { "user": { "name": "Alice" } }

# Using xmlstarlet + jq
xmlstarlet sel -t -v '//name' input.xml | jq -R '{ name: . }'

# Node.js one-liner with xml2js
echo '<a><b>1</b></a>' | node -e "
  const {parseString} = require('xml2js');
  let d=''; process.stdin.on('data',c=>d+=c);
  process.stdin.on('end',()=>parseString(d,(e,r)=>console.log(JSON.stringify(r,null,2))))
"

Frequently Asked Questions

Is XML to JSON conversion lossless?
Not always. XML attributes, comments, processing instructions, and namespace declarations have no direct JSON equivalent. Most converters preserve attributes using an @-prefix convention, but comments and processing instructions are discarded. If you need a fully reversible round-trip, use a lossless convention like BadgerFish.
How are XML attributes represented in JSON?
The most common approach is to prefix attribute names with @. For example, <book id="1"> becomes {"@id": "1"}. Some converters use a nested "_attributes" object instead. The specific convention depends on the library you use.
How does the converter handle repeated XML elements?
When an element appears more than once under the same parent, the converter groups them into a JSON array. For example, two item siblings become {"item": ["a", "b"]}. A single item element stays as a plain string value unless force-array mode is enabled.
Can I convert JSON back to XML?
Yes, but the result depends on the convention used during the original conversion. If attributes were preserved with @ prefixes, a JSON-to-XML converter can reconstruct them. If the original conversion used Parker (which drops attributes), that information is gone. ToolDeck also has a JSON to XML tool for the reverse direction.
What happens to XML namespaces during conversion?
Namespace handling varies by library. Some converters preserve the prefix in the key name (e.g., "ns:element"), others map xmlns declarations to separate fields, and some strip namespaces entirely. Check the output for your specific XML to verify namespace behavior.
Is there a standard for XML to JSON conversion?
There is no formal W3C or IETF standard. The closest references are the BadgerFish convention, the Parker convention, and the OASIS XSLT-to-JSON mapping. In practice, each library implements its own rules, which is why the same XML can produce slightly different JSON in different tools.
How do I handle large XML files?
Browser-based converters work well for files up to a few megabytes. For larger files (10MB+), use a streaming parser like Python's iterparse (xml.etree.ElementTree) or Node.js xml-stream. These process the document incrementally without loading the entire tree into memory.