How to Convert XML to JSON: Overcoming Attributes, Array Coercion, and Namespaces
Practical guide to transforming XML into clean JSON: handling attributes vs elements, array coercion traps, namespace stripping, and implementation recipes.
The XML to JSON Impedance Mismatch
Converting XML documents into clean, developer-friendly JSON is challenging because XML and JSON model data with fundamentally different primitives. XML supports attributes on tags, mixed text-node children, namespaces, and unordered repeating elements. JSON only supports string keys mapped to primitives, arrays, or sub-objects.
The 3 Major Conversion Challenges
- Attributes vs Elements: An XML tag like
<user id="42">John</user>has both an attribute (id) and text content (John). In JSON, this is typically converted using a prefix convention (e.g.{"@id": 42, "#text": "John"}). - Array Coercion Trap: If an XML element has multiple child tags
<item>1</item><item>2</item>, parsers output an array[1, 2]. However, if only one<item>1</item>exists, naive parsers output a single object{item: 1}instead of[1], breaking downstream array iteration. - Type Inference: XML stores numbers and booleans as text strings. Modern converters must intelligently parse
"true"as booleantrueand"42"as number42without corrupting leading-zero strings like postal codes ("07030").
1. Converting XML in Node.js (fast-xml-parser)
fast-xml-parser is the gold standard for high-speed XML parsing in Node.js and TypeScript. It supports attribute prefixes, automatic number parsing, and explicit array guarantees:
import { XMLParser } from 'fast-xml-parser';
const xmlData = `
<store name="CoShareX Depot">
<book id="101">
<title>High Performance WebRTC</title>
<price>39.99</price>
</book>
<book id="102">
<title>Client-Side Cryptography</title>
<price>49.99</price>
</book>
</store>`;
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '@_',
parseAttributeValue: true,
parseTagValue: true,
isArray: (tagName) => tagName === 'book' // Guarantee array even if 1 book
});
const jsonOutput = parser.parse(xmlData);
console.log(JSON.stringify(jsonOutput, null, 2));2. Converting XML in Python (xmltodict)
import json
import xmltodict
xml_content = """
<catalog>
<product sku="A123">
<name>Mechanical Keyboard</name>
<in_stock>true</in_stock>
</product>
</catalog>
"""
# Parse XML to Python Dictionary
data_dict = xmltodict.parse(
xml_content,
attr_prefix="@",
force_list={'product'} # Ensure product is always a list
)
# Serialize to formatted JSON
json_output = json.dumps(data_dict, indent=2)
print(json_output)3. Pure Browser Approach (DOMParser)
In client-side applications without external libraries, you can parse XML using the native DOMParser API and recursively traverse the DOM tree into a JavaScript object:
function xmlToDom(xmlString) {
const parser = new DOMParser();
const doc = parser.parseFromString(xmlString, 'text/xml');
// Check for parser errors
const parseError = doc.querySelector('parsererror');
if (parseError) throw new Error('XML parsing failed: ' + parseError.textContent);
return doc.documentElement;
}Code Formatter & Converter Suite
Validate, format, minify, and convert JSON, SQL, YAML, XML, and code dialects directly on your local machine.
Frequently Asked Questions
How do I handle CDATA sections when converting XML to JSON?
CDATA blocks (`<![CDATA[...]]>`) contain raw unparsed character data. Modern parsers extract the inner text of CDATA blocks as standard JSON strings, automatically escaping quotes and newlines.
Can XML namespaces be preserved in JSON?
Yes. Parsers can either preserve prefix keys (e.g. `"soap:Envelope"`) or strip namespace prefixes to produce clean, uncluttered JSON schemas.
Conclusion
If the input XML has multiple sibling tags with the same name, standard XML parsers group them into a single JSON array under that tag name. For example, multiple `<role>` tags will convert to a single `"role": [...]` array in the JSON output.
Related Articles
How to Validate JSON: Syntax Diagnostics, JSON Schema (Draft 2020-12), and Runtime Validation
Learn how to validate JSON data: debugging syntax errors, defining JSON Schema (Draft 2020-12) contracts, and validating runtime payloads with Ajv, Zod, and Pydantic.
Developer ToolsJSON vs XML: Structural Architecture, Parsing Performance, and Modern Use Cases
A deep architectural comparison between JSON and XML: data types, schema validation (JSON Schema vs XSD), payload overhead, and parsing performance.
ConvertersHow to Convert YAML to JSON: Anchors, Multiline Strings, and the Norway Problem
Master YAML to JSON conversion: understand YAML 1.2 superset features, anchor references, multiline block scalars, and safe parsing in Node.js and Python.