Table of contents
XML was the dominant data format for web services and configuration through the 2000s. JSON took over for most new API and web work after 2010. But XML has not disappeared — enterprise systems, SOAP services, RSS feeds, and configuration files still use it everywhere. When you need to move data from an XML source into a modern JSON-based system, conversion is the most practical path.
This guide explains how XML-to-JSON conversion works, what decisions the converter has to make, and how to handle common edge cases.
Why convert XML to JSON?
XML and JSON represent structured data differently, and each has strengths:
XML is better for:
- Documents with mixed content (text and markup interleaved)
- Schemas and validation with DTD or XML Schema
- Namespaced data from multiple sources
- SOAP web services and enterprise systems
JSON is better for:
- REST API payloads
- JavaScript and web frontend consumption
- Lightweight data exchange
- Human readability in most cases
The typical conversion scenario: you have an XML data source (a legacy API, an exported feed, a configuration file) and you need to feed that data into a modern JavaScript app, REST API, or JSON-based database. Rather than writing a custom parser, a converter handles the structural mapping automatically.
How to convert XML to JSON
- Go to the XML to JSON Converter on FixTools
- Paste your XML or upload the file
- Get the JSON output — the tool maps elements, attributes, and text content to JSON structures
- Copy and use the result — paste into your code, database, or API payload
The conversion is immediate and runs in your browser — no data is uploaded to a server.
How XML maps to JSON
XML and JSON have different mental models. Understanding the mapping helps you predict the output and spot conversion issues.
Simple elements
The simplest case converts cleanly:
XML:
<person>
<name>Alice</name>
<age>30</age>
</person>
JSON:
{
"person": {
"name": "Alice",
"age": "30"
}
}
Note that age becomes the string "30" — XML has no numeric type, so all values are strings by default. Some converters attempt type inference and convert numbers and booleans automatically.
Repeating elements (arrays)
XML represents sequences through repeated sibling elements. Converters map these to JSON arrays:
XML:
<users>
<user>Alice</user>
<user>Bob</user>
<user>Carol</user>
</users>
JSON:
{
"users": {
"user": ["Alice", "Bob", "Carol"]
}
}
Important edge case: If there is only one <user> element, some converters output a single string instead of a one-element array:
{
"users": {
"user": "Alice"
}
}
This inconsistency breaks code that expects an array. If you consume converted XML in code, normalize single values to arrays defensively.
Attributes
XML attributes have no JSON equivalent. Converters handle them differently:
XML:
<product id="42" category="electronics">Laptop</product>
Common JSON output (attribute prefix approach):
{
"product": {
"@id": "42",
"@category": "electronics",
"#text": "Laptop"
}
}
The @ prefix marks attributes, and #text holds the element's text content. Some converters use different conventions (_attributes, $, or merging attributes directly with content keys).
Nested elements
Deep XML hierarchies convert to nested JSON objects:
XML:
<order>
<customer>
<name>Alice</name>
<address>
<city>London</city>
<country>UK</country>
</address>
</customer>
<total>99.50</total>
</order>
JSON:
{
"order": {
"customer": {
"name": "Alice",
"address": {
"city": "London",
"country": "UK"
}
},
"total": "99.50"
}
}
Namespaces
XML namespaces (xmlns prefixes like <soap:Body>) have no JSON equivalent. Most converters preserve the prefix as part of the key name:
{
"soap:Envelope": {
"soap:Body": { ... }
}
}
If namespaces are not relevant to your use case, you may want to strip them after conversion.
After conversion: clean up the JSON
Raw XML-to-JSON output often needs a few adjustments before it is useful:
Extract the root element
XML always has a single root element that wraps everything. Your JSON output will have this as a top-level key. If you are building an API response, you probably want the content inside the root, not the root wrapper itself.
// Before
const data = xmlToJson(xmlString);
// { "orders": { "order": [...] } }
// After — strip the root wrapper
const orders = data.orders.order;
Normalize arrays
Convert single-item pseudo-arrays to real arrays using a helper:
function toArray(val) {
if (val === undefined || val === null) return [];
return Array.isArray(val) ? val : [val];
}
const items = toArray(data.items.item);
Convert types
XML text content is always a string. Convert numbers and booleans:
const price = parseFloat(item.price);
const inStock = item.inStock === 'true';
Use the JSON Formatter
After conversion, paste the result into the FixTools JSON Formatter to check structure and make it easier to read. Use the JSON Validator to catch any syntax issues before feeding the data into your application.
Common XML-to-JSON conversion problems
Mixed content
XML supports text mixed with child elements in the same element:
<description>Check the <strong>new</strong> features.</description>
This mixed content does not have a clean JSON equivalent. Converters usually either lose the inline markup or produce awkward structures like {"description": {"#text": "Check the ", "strong": "new"}}.
If your XML contains mixed content (common in document-style XML), JSON may not be the right target format. Consider using HTML or Markdown instead.
CDATA sections
XML CDATA sections contain literal text that should not be parsed as XML:
<script><![CDATA[if (a < b) { ... }]]></script>
Most converters treat CDATA content as plain text and output it as a string value. Check that angle brackets and special characters inside CDATA survive the conversion correctly.
Large files
Browser-based converters work well for files up to a few megabytes. For large XML exports — multi-megabyte feeds, database dumps, or log files — use a command-line tool:
# Using xq (jq for XML)
cat data.xml | xq . > data.json
# Using Python xmltodict
python3 -c "import xmltodict, json, sys; print(json.dumps(xmltodict.parse(sys.stdin.read()), indent=2))" < data.xml
Character encoding
XML files can declare a character encoding like UTF-8, ISO-8859-1, or Windows-1252. JSON is always UTF-8. If your XML uses a non-UTF-8 encoding, ensure the converter or your toolchain handles the conversion correctly — otherwise you may see garbled characters in string values.
XML to JSON in code
If you are automating XML-to-JSON conversion in your application, here are the standard library approaches:
JavaScript (Node.js):
import { xml2js } from 'xml-js';
const json = xml2js(xmlString, { compact: true, spaces: 2 });
Python:
import xmltodict
import json
with open('data.xml') as f:
data = xmltodict.parse(f.read())
print(json.dumps(data, indent=2))
Browser (vanilla JavaScript):
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
function xmlToObj(node) {
const obj = {};
for (const child of node.children) {
const key = child.tagName;
const value = child.children.length > 0 ? xmlToObj(child) : child.textContent;
obj[key] = obj[key]
? [...(Array.isArray(obj[key]) ? obj[key] : [obj[key]]), value]
: value;
}
return obj;
}
Convert XML to JSON now
Paste your XML into the FixTools XML to JSON Converter and get clean JSON output instantly. Use the JSON Formatter to verify the structure and JSON Validator to catch any issues. No sign-up or installation required.
Try it free — right in your browser
No sign-up, no uploads. Your data stays private on your device.
Frequently asked questions
6 questions answered
QWhat happens to XML attributes when converting to JSON?
XML attributes (like <item id="1">) have no direct equivalent in JSON. Different converters handle this differently. A common approach is to prefix the attribute name with @ and include it as a key alongside the element content — for example, {"item": {"@id": "1", "#text": "value"}}. Some converters use a dedicated _attributes object. When doing XML-to-JSON conversion for an API, check how your target system expects attributes to be represented and choose a converter that matches that behavior. If the XML uses attributes heavily, the resulting JSON can become quite verbose.
QWhy does XML result in more deeply nested JSON than expected?
XML wraps everything in elements, even simple text values. An XML element like <name>Alice</name> often converts to {"name": "Alice"} in JSON. But if the element has attributes, the converter needs an object structure instead of a plain string — so it becomes {"name": {"@value": "Alice"}}. XML documents designed with verbose element structures produce nested JSON that can feel over-engineered. If you control the XML, simplifying the structure before conversion often produces cleaner JSON output.
QHow are XML arrays handled in JSON conversion?
XML does not have a native array type — repeating elements represent sequences. For example, multiple <item> elements in a list are a sequence in XML. Converters typically detect repeated sibling elements with the same tag name and output them as a JSON array. If there is only a single <item> element, some converters output an object instead of a one-element array, which can cause parsing errors in code expecting an array. When writing code that consumes converted XML, always normalize single-item responses to arrays defensively.
QIs there any information lost when converting XML to JSON?
Yes, potentially. XML supports several features JSON does not have: XML namespaces (xmlns prefixes), XML comments, CDATA sections, processing instructions, and document type declarations (DOCTYPE). JSON has none of these concepts. Most converters strip comments and processing instructions silently. Namespaces may be preserved as prefixes in key names or dropped, depending on the converter. For round-trip conversion (XML → JSON → XML), this information loss means the XML you get back may not be identical to what you started with.
QCan I convert a large XML file to JSON?
Browser-based converters handle most everyday XML files (under a few megabytes) without issues. For large files — multi-megabyte exports from enterprise systems, data feeds, or log files — browser-based tools may be slow or hit memory limits. For large-scale XML processing, command-line tools like xq (a jq wrapper for XML) or language libraries (Python xmltodict, Node xml2js) are more appropriate. They can handle streaming parsing for files too large to load into memory at once.
QWhat is the difference between XML and JSON for APIs?
JSON has largely replaced XML as the preferred data format for REST APIs because it is lighter (no opening and closing tags), easier to parse in JavaScript, and more readable for human debugging. XML is still common in enterprise systems, SOAP web services, RSS and Atom feeds, and legacy APIs. Many older APIs accept both formats — you request JSON by setting the Accept: application/json header. For new API work, JSON is the default. For integration with systems that only speak XML, conversion is the practical approach rather than rewriting the source system.
O. Kimani
Software Developer & Founder, FixTools
Building FixTools — a single destination for free, browser-based productivity tools. Every tool runs client-side: your files never leave your device.
About the authorRelated articles
Best Free JSON Formatter and Validator Online (2026)
Format messy JSON instantly and catch syntax errors before they break your app. Free browser-based JSON formatter and validator. No signup, no install.
Read articleDeveloper & WebHow to Convert CSV to JSON Online (Free & Instant)
Convert a CSV file or spreadsheet export to valid JSON in seconds. Learn the format differences, conversion rules, and how to handle edge cases like nested data and special characters.
Read article