This free XML to JSON converter runs in your browser. Paste XML or choose a local XML file, pick your output options, and convert it to formatted or compact JSON. Copy the result or download it as a .json file. The converter code does not send your XML to a conversion API.
Short answer: an XML element becomes a JSON property, repeated sibling elements become an array, and attributes become properties with an @ prefix. Text-only elements become strings. When meaningful text and child elements are interleaved, this converter stores them in an ordered #content array so their sequence is not lost. Whitespace-only ordinary text nodes are omitted by default unless xml:space="preserve" applies; CDATA content is retained as text. All XML text and attribute values remain strings.
Paste XML or drop a file, click Convert, then copy or download the JSON. Supports UTF-8, UTF-16 and declared encodings. Maximum input: 2 MiB.
No file selected. You can also drag a file here.
How to read this JSON
- @name is an XML attribute.
- #text is element text that sits next to attributes.
- #content keeps text and child elements in their original order (mixed content).
- Repeated sibling elements become an array. Turn on "Always use arrays" for a fixed shape.
- Every value is a string. Numbers, booleans and dates are not guessed.
- Comments, processing instructions, the XML declaration and namespace prefixes are not included, so this is not a lossless copy of the XML.
The converted JSON will appear here.
How to use the XML to JSON converter
- Paste your XML into the input box, or choose an XML file saved on your device. You can select Load sample to try the converter without preparing a file.
- Leave Always represent child elements as arrays unchecked to create arrays only when sibling elements repeat. Enable it when your application expects an array even when the XML contains only one matching element.
- Select Convert to JSON for readable, indented output or Convert compact for a single-line result.
- Copy the JSON, download it as
converted.json, or use Validate JSON to check the editable output.
If you load the sample and convert it, you should see an orders object containing one order with @id and @status properties and an item array with two entries. The converter keeps the previous JSON visible when a conversion fails, but it warns you that the output may no longer represent the current XML. Convert again after correcting the input.
How this XML to JSON converter maps XML
XML and JSON have different data models, so there is no single universal mapping. This tool uses the rules below. They are consistent and preserve important information where possible, but the output is not a lossless copy of the original XML document.
For each element, the converter asks four questions in a fixed order. The flowchart below shows that order, and the table after it lists every rule.
@ keys.| XML content | JSON representation | Example |
|---|---|---|
| Text-only element | String | <name>Asha</name> → "name": "Asha" |
| Nested elements | Nested object | <a><b>1</b></a> → "a": {"b": "1"} |
| Attribute | Property prefixed with @ | id="7" → "@id": "7" |
| Attribute-only element | Object containing attributes; no #text property when no text node exists | <a id="7"/> → {"@id":"7"} |
| Text plus attributes | Object with attributes and #text | <p id="1">Hi</p> → {"@id":"1","#text":"Hi"} |
| Repeated sibling elements | Array | Two <item> elements become "item": [...] |
| Single child with array option enabled | One-item array | "item": ["Keyboard"] |
| Empty element | Empty string | <empty/> → "empty": "" |
| Mixed text and child elements | Ordered #content array | Text and child elements remain in document order |
| Namespaced element | Expanded name containing namespace URI | {urn:catalog}Entry |
| Namespaced attribute | @ followed by its expanded name | @{urn:meta}id |
Namespace declarations (xmlns, xmlns:prefix) | Omitted | The namespace URI already appears in the expanded names |
| XML comments and processing instructions | Dropped | JSON has no direct equivalent in this mapping |
| XML declaration | Dropped | <?xml version="1.0"?> does not appear in the output |
| CDATA section | Text value | CDATA markers are removed; the contained text is retained. CDATA text is treated as character data even when it contains only whitespace. |
Mapping compatibility note: older versions of this converter used underscore-prefixed attributes (for example _id) and X2JS metadata keys. This version uses @id for attributes, namespace-qualified names such as {urn:example}Entry, and #content for mixed content. If you saved output from an older version, re-convert it before comparing.
XML to JSON example, step by step
Consider this XML document describing an article. The XML declaration identifies the XML version and encoding. It is not represented in the JSON output.
XML input
<catalog>
<article id="C001">
<author>Nikunj Satasiya</author>
<title>XML to JSON Converter Online</title>
<genre>Computer</genre>
<price>$39.33</price>
<publisher>Codingvila</publisher>
<publish_date>2022-07-02</publish_date>
<description>Convert XML to JSON with this free online converter.</description>
</article>
</catalog>
Converted JSON
{
"catalog": {
"article": {
"@id": "C001",
"author": "Nikunj Satasiya",
"title": "XML to JSON Converter Online",
"genre": "Computer",
"price": "$39.33",
"publisher": "Codingvila",
"publish_date": "2022-07-02",
"description": "Convert XML to JSON with this free online converter."
}
}
}
The root element catalog becomes the top-level property. Its child article becomes an object, while the id attribute becomes @id. The price and date remain strings; the converter does not guess application-specific data types.
Convert XML with attributes and repeated elements
Repeated sibling elements are one of the most important cases to handle correctly. In this example, an order contains two item elements, and each item has attributes and text.
<orders>
<order id="A100" status="shipped">
<customer>Asha Patel</customer>
<item sku="KB-01" qty="1">Keyboard</item>
<item sku="MS-02" qty="2">Mouse</item>
<total currency="USD">74.98</total>
</order>
</orders>
Because item occurs twice, it becomes an array. Each item also has attributes and text, so its JSON value is an object.
{
"orders": {
"order": {
"@id": "A100",
"@status": "shipped",
"customer": "Asha Patel",
"item": [
{
"@sku": "KB-01",
"@qty": "1",
"#text": "Keyboard"
},
{
"@sku": "MS-02",
"@qty": "2",
"#text": "Mouse"
}
],
"total": {
"@currency": "USD",
"#text": "74.98"
}
}
}
}
When the XML contains only one item, the default output is a single object rather than an array. Enable Always represent child elements as arrays when your application requires a stable array shape even for one item.
Preserving mixed-content order
Mixed content occurs when text and child elements appear between the same element's opening and closing tags. For example:
<p>Hello <b>bold</b> world</p>
A simple object mapping that stores all text in one property can lose the original sequence. This converter instead uses #content to retain the order of text and child elements:
{
"p": {
"#content": [
"Hello ",
{ "b": "bold" },
" world"
]
}
}
When an element contains only nested elements and formatting whitespace, whitespace-only ordinary text nodes are omitted by default because they commonly represent indentation. When meaningful text or CDATA is interleaved with child elements, all text and CDATA nodes are retained in sequence, including whitespace-only ordinary text nodes between those children. Set xml:space="preserve" to retain whitespace-only ordinary text nodes in an element and its descendants; xml:space="default" resets that behavior for the element and its descendants. CDATA content is retained as text even when it contains only whitespace. XML comments and processing instructions are not included, and CDATA markers are not preserved.
XML namespaces and SOAP data
XML namespace prefixes are aliases for namespace URIs. Two elements can have different prefixes but represent the same expanded name if their namespace URIs are identical. Conversely, two elements with the same local name can represent different names when their namespace URIs differ. The Namespaces in XML 1.0 specification defines these rules.
This converter uses expanded names in the form {namespace-uri}local-name. Namespace declaration attributes such as xmlns:s are not copied as ordinary attributes because the namespace URI is already included in the element or attribute name. Attributes in the reserved xml: prefix, such as xml:lang, also receive an expanded name, @{http://www.w3.org/XML/1998/namespace}lang.
<root xmlns:a="urn:first" xmlns:b="urn:second">
<a:Entry>First</a:Entry>
<b:Entry>Second</b:Entry>
</root>
The JSON keeps the two namespace identities separate:
{
"root": {
"{urn:first}Entry": "First",
"{urn:second}Entry": "Second"
}
}
Namespace prefixes are not retained as prefixes. The URI is retained in the property name instead. This is useful when comparing expanded names, but it does not make the JSON a complete, reversible representation of the original XML document. Check your SOAP service's namespace and schema requirements before using converted data in production.
The XML xml:space attribute is retained as an expanded-name attribute and also influences whitespace processing. Its preserve value is inherited by descendants unless an element sets xml:space="default".
Common XML-to-JSON problems and how to fix them
The converter says the XML is not well formed
Well-formed XML follows the syntax rules in the XML 1.0 specification. Common causes include an unclosed tag, tags closed in the wrong order, unquoted attribute values, multiple root elements, and unescaped special characters. For example, <n>AT&T</n> is invalid because the ampersand starts an entity reference. Use <n>AT&T</n> instead. Use < for a literal less-than character in text.
The exact parser message differs between browsers, because each browser's XML parser words its errors differently. The line and column it reports are usually the quickest way to find the problem.
The XML declaration causes an error in another tool
The XML declaration (<?xml ...?>) must be the very first thing in a document. A blank line or space before it is an error in strict parsers. This converter trims leading whitespace and a byte order mark from pasted input, but other tools may not, so remove it from the source file.
A single item is not an array
By default, the converter creates an array when two or more sibling elements share the same name. One occurrence remains a scalar or object. Enable the always-array option when your application expects a predictable array shape.
When consuming output from a converter that does not provide an always-array option, you can normalize the value in JavaScript:
const items = [].concat(data.order.item ?? []);
If item is already an array, concat returns a copy. If it is a single object or string, it is wrapped in an array. If it is missing, the result is an empty array.
Numbers and booleans come out as strings
XML element text and attribute values are text. A value such as <qty>2</qty> becomes "2", not the JSON number 2. Convert values in your application only after checking the expected field and its valid range. Do not automatically parse every numeric-looking string; identifiers, postal codes and account numbers may need to remain strings.
Whitespace changes between XML and JSON
This converter preserves text in text-only elements, including leading and trailing spaces. When an element contains only child elements, whitespace-only ordinary text nodes are treated as formatting whitespace and omitted by default. CDATA nodes are retained as character data. If an element contains meaningful text or CDATA mixed with child elements, all text and CDATA nodes are retained in their original sequence. Use xml:space="preserve" when whitespace-only content must be kept, and xml:space="default" to reset inherited preservation. The xml:space attribute is also included in the JSON output as an expanded-name attribute. Test representative documents when whitespace is significant to your format.
Special characters look garbled
The file picker reads files as UTF-8. If your XML file was saved in another encoding, such as UTF-16 or Windows-1252, accented letters and symbols can appear damaged. Re-save the file as UTF-8 and load it again.
CDATA does not appear as a separate JSON type
JSON has no CDATA construct. The converter retains the text inside a CDATA section as an ordinary string, but it does not record whether the original text came from CDATA or a normal XML text node.
What happens to XML comments and processing instructions?
They are omitted from the output because this converter focuses on element data, attributes and text. The XML declaration is also not represented. If you need to preserve comments, processing instructions, lexical details or exact document formatting, use an XML-aware archival or transformation workflow instead of a simple object mapping.
Why are DOCTYPE declarations rejected?
This browser tool rejects documents containing a DOCTYPE/DTD declaration. DTDs can define custom entities and introduce unnecessary parser risks for an online utility. Standard predefined XML entities and numeric character references are supported by the browser's XML parser. Remove the DTD and replace custom entity references with their intended text before converting.
What if the XML file is very large?
The browser tool limits input to 2 MiB, 100,000 elements and a nesting depth of 128. These limits reduce the risk of freezing a browser tab, but they do not guarantee that every device will process a document equally quickly. For larger files, use a local script or application with appropriate memory and input limits.
Convert XML to JSON in JavaScript (browser)
You can build a basic converter with the browser's built-in DOMParser and no library. Paste the code below into your browser's developer console or a script file to try it.
function elementToJson(element) {
const result = Object.create(null);
for (const attribute of Array.from(element.attributes)) {
result[`@${attribute.name}`] = attribute.value;
}
const children = Array.from(element.children);
if (children.length === 0) {
const text = element.textContent;
if (Object.keys(result).length === 0) return text;
if (text) result["#text"] = text;
return result;
}
for (const child of children) {
const value = elementToJson(child);
if (child.nodeName in result) {
result[child.nodeName] = [].concat(result[child.nodeName], [value]);
} else {
result[child.nodeName] = value;
}
}
return result;
}
const xml = `<order id="A100">
<customer>Asha Patel</customer>
<item sku="KB-01">Keyboard</item>
<item sku="MS-02">Mouse</item>
</order>`;
function hasDoctypeDeclaration(source) {
const tokens = source.matchAll(/<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE\b/gi);
for (const token of tokens) {
if (/^<!DOCTYPE/i.test(token[0])) return true;
}
return false;
}
if (hasDoctypeDeclaration(xml)) {
throw new Error("DOCTYPE/DTD declarations are not supported.");
}
if (typeof DOMParser === "undefined") {
throw new Error("This browser does not support DOMParser.");
}
const xmlDocument = new DOMParser().parseFromString(xml, "application/xml");
const rootNode = xmlDocument.documentElement;
const parserErrorMessage = rootNode ? rootNode.textContent || "" : "";
const knownParserErrorNamespace = rootNode && [
"http://www.w3.org/1999/xhtml",
"http://www.mozilla.org/newlayout/xml/parsererror.xml"
].includes(rootNode.namespaceURI);
const hasParserError = rootNode && rootNode.localName === "parsererror" &&
(knownParserErrorNamespace || !rootNode.namespaceURI) &&
/xml parsing error|this page contains the following errors|error on line|not well-formed|mismatched tag|failed to parse xml|unexpected end of file|unclosed token|invalid token/i.test(parserErrorMessage);
if (hasParserError) {
throw new Error("The XML is not well formed.");
}
const root = xmlDocument.documentElement;
console.log(JSON.stringify({ [root.nodeName]: elementToJson(root) }, null, 2));
The function reads attributes first, then returns a string for text-only elements, or recurses into child elements. When a child name repeats, the value is turned into an array. Expected console output:
{
"order": {
"@id": "A100",
"customer": "Asha Patel",
"item": [
{
"@sku": "KB-01",
"#text": "Keyboard"
},
{
"@sku": "MS-02",
"#text": "Mouse"
}
]
}
}
This is a deliberately small educational example. It rejects DTD declarations and malformed XML, but it keeps namespace prefixes rather than namespace URIs, drops text that sits next to child elements, does not implement xml:space, and has no input-size, element-count or depth limits. Do not use this abbreviated snippet as a production parser for untrusted or large XML. Use the converter above or a maintained XML library for those cases.
Convert XML to JSON using Node.js
For scheduled jobs, command-line workflows or server-side applications, use a dedicated XML parser. This example uses fast-xml-parser version 5.12.0. It validates the XML, rejects DTD declarations, keeps attributes and text values as strings, drops the XML declaration, forces every element named item to be an array, and writes a JSON file. Use a currently supported Node.js LTS release.
First, save this sample as orders.xml:
<orders>
<order id="A100" status="shipped">
<customer>Asha Patel</customer>
<item sku="KB-01" qty="1">Keyboard</item>
<item sku="MS-02" qty="2">Mouse</item>
<total currency="USD">74.98</total>
</order>
</orders>
Install the package in an empty project folder. Installing fast-xml-parser@5.12.0 records the exact version in package-lock.json; commit that file so a future release does not silently change your results.
npm install fast-xml-parser@5.12.0
node convert.mjs orders.xml orders.json
Save the following as convert.mjs. The script expects UTF-8 input and limits it to 5 MiB.
import { readFile, stat, writeFile } from "node:fs/promises";
import { TextDecoder } from "node:util";
import { XMLParser, XMLValidator } from "fast-xml-parser";
const MAX_FILE_BYTES = 5 * 1024 * 1024;
const MAX_ELEMENTS = 100000;
const MAX_DEPTH = 128;
// Scans left to right so a DOCTYPE inside a comment, CDATA or processing instruction is ignored.
const TOKEN_PATTERN = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE\b/gi;
function hasDoctype(xml) {
for (const match of xml.matchAll(TOKEN_PATTERN)) {
if (/^<!DOCTYPE/i.test(match[0])) return true;
}
return false;
}
function findMarkupEnd(xml, startIndex) {
let quote = "";
for (let i = startIndex; i < xml.length; i += 1) {
const character = xml[i];
if (quote) {
if (character === quote) quote = "";
} else if (character === '"' || character === "'") {
quote = character;
} else if (character === ">") {
return i;
}
}
throw new Error("XML contains an unterminated tag.");
}
function enforceStructureLimits(xml) {
let depth = 0;
let elements = 0;
let index = 0;
while (index < xml.length) {
if (xml[index] !== "<") {
index += 1;
continue;
}
if (xml.startsWith("<!--", index)) {
const end = xml.indexOf("-->", index + 4);
index = end < 0 ? xml.length : end + 3;
continue;
}
if (xml.startsWith("<![CDATA[", index)) {
const end = xml.indexOf("]]>", index + 9);
index = end < 0 ? xml.length : end + 3;
continue;
}
if (xml.startsWith("<?", index)) {
const end = xml.indexOf("?>", index + 2);
index = end < 0 ? xml.length : end + 2;
continue;
}
const end = findMarkupEnd(xml, index + 1);
if (xml.startsWith("</", index)) {
// A malformed stray closing tag must not offset later opening tags.
if (depth > 0) depth -= 1;
} else if (!xml.startsWith("<!", index)) {
elements += 1;
if (elements > MAX_ELEMENTS) {
throw new Error(`XML contains more than ${MAX_ELEMENTS} elements.`);
}
let last = end - 1;
while (last > index && /\s/.test(xml[last])) last -= 1;
if (xml[last] !== "/") {
depth += 1;
if (depth > MAX_DEPTH) {
throw new Error(`XML nesting depth exceeds ${MAX_DEPTH}.`);
}
}
}
index = end + 1;
}
}
async function main() {
const [inputPath, outputPath] = process.argv.slice(2);
if (!inputPath || !outputPath) {
throw new Error("Usage: node convert.mjs <input.xml> <output.json>");
}
const fileInfo = await stat(inputPath);
if (fileInfo.size > MAX_FILE_BYTES) {
throw new Error("Input XML must be 5 MiB or smaller.");
}
const xmlBytes = await readFile(inputPath);
const xml = new TextDecoder("utf-8", { fatal: true }).decode(xmlBytes).replace(/^\uFEFF/, "");
if (hasDoctype(xml)) {
throw new Error("DOCTYPE/DTD declarations are not supported.");
}
enforceStructureLimits(xml);
const validation = XMLValidator.validate(xml);
if (validation !== true) {
const details = validation.err ?? {};
throw new Error(
`Invalid XML at line ${details.line ?? "?"}, column ${details.col ?? "?"}: ${details.msg ?? "XML validation failed"}`
);
}
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: "@_",
textNodeName: "#text",
parseTagValue: false,
parseAttributeValue: false,
trimValues: true,
ignoreDeclaration: true,
ignorePiTags: true,
isArray: (tagName) => tagName === "item"
});
const data = parser.parse(xml);
const json = JSON.stringify(data, null, 2) + "\n";
await writeFile(outputPath, json, "utf8");
console.log(`Wrote ${outputPath}`);
}
main().catch((error) => {
console.error(error.message);
process.exitCode = 1;
});
The terminal prints Wrote orders.json, and orders.json contains the following. Key order inside an object, such as where #text sits relative to the attributes, can vary between library versions.
{
"orders": {
"order": {
"@_id": "A100",
"@_status": "shipped",
"customer": "Asha Patel",
"item": [
{
"@_sku": "KB-01",
"@_qty": "1",
"#text": "Keyboard"
},
{
"@_sku": "MS-02",
"@_qty": "2",
"#text": "Mouse"
}
],
"total": {
"@_currency": "USD",
"#text": "74.98"
}
}
}
}
In this example, attributes use the @_ prefix and text next to attributes uses #text. The isArray callback matches the element name item wherever it appears in the document, not just under one specific parent. Without ignoreDeclaration, this library adds a ?xml key for the XML declaration. This library's shape differs from the browser converter above, so choose one mapping convention for an application and keep it consistent.
Convert XML to Python JSON using xmltodict
Python's xmltodict package converts XML into dictionary structures that can be serialized as JSON. This example needs Python 3.9 or later and xmltodict 1.0.4. It reads UTF-8 XML, rejects DTD declarations, disables entity expansion, forces item to remain a list, and writes UTF-8 JSON. Use the same orders.xml file from the Node.js section.
Create a virtual environment so the package stays out of your system Python, then install the exact version used for this example. For production, keep the pinned version in a requirements file and update it deliberately after testing.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install xmltodict==1.0.4
python convert.py orders.xml orders.json
Save the following script as convert.py:
import json
import re
import sys
from pathlib import Path
from xml.parsers.expat import ExpatError, ParserCreate, XML_PARAM_ENTITY_PARSING_NEVER
import xmltodict
MAX_FILE_BYTES = 5 * 1024 * 1024
MAX_ELEMENTS = 100000
MAX_DEPTH = 128
# Scans left to right so a DOCTYPE inside a comment, CDATA or processing instruction is ignored.
TOKEN_PATTERN = re.compile(
r"<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE\b",
re.IGNORECASE,
)
def has_doctype(xml_text: str) -> bool:
return any(
match.group(0).upper().startswith("<!DOCTYPE")
for match in TOKEN_PATTERN.finditer(xml_text)
)
def validate_xml_limits(xml_text: str) -> None:
"""Parse once with Expat to enforce nesting and element-count limits."""
depth = 0
element_count = 0
parser = ParserCreate()
parser.SetParamEntityParsing(XML_PARAM_ENTITY_PARSING_NEVER)
def start_element(name: str, attributes: dict) -> None:
nonlocal depth, element_count
depth += 1
element_count += 1
if depth > MAX_DEPTH:
raise ValueError(f"XML nesting depth exceeds {MAX_DEPTH}.")
if element_count > MAX_ELEMENTS:
raise ValueError(f"XML contains more than {MAX_ELEMENTS} elements.")
def end_element(name: str) -> None:
nonlocal depth
depth -= 1
parser.StartElementHandler = start_element
parser.EndElementHandler = end_element
try:
parser.Parse(xml_text, True)
except ExpatError as exc:
raise ValueError(f"Invalid XML: {exc}") from exc
def convert_xml_to_json(input_path: str, output_path: str) -> None:
source = Path(input_path)
if source.stat().st_size > MAX_FILE_BYTES:
raise ValueError("Input XML must be 5 MiB or smaller.")
xml_text = source.read_text(encoding="utf-8-sig")
if has_doctype(xml_text):
raise ValueError("DOCTYPE/DTD declarations are not supported.")
validate_xml_limits(xml_text)
try:
data = xmltodict.parse(
xml_text,
attr_prefix="@_",
cdata_key="#text",
force_list=("item",),
disable_entities=True,
strip_whitespace=True,
)
except ExpatError as exc:
raise ValueError(f"Invalid XML: {exc}") from exc
destination = Path(output_path)
destination.write_text(
json.dumps(data, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
def main() -> None:
if len(sys.argv) != 3:
raise SystemExit("Usage: python convert.py input.xml output.json")
try:
convert_xml_to_json(sys.argv[1], sys.argv[2])
print(f"Wrote {sys.argv[2]}")
except (OSError, ValueError) as error:
print(error, file=sys.stderr)
raise SystemExit(1) from error
if __name__ == "__main__":
main()
The terminal prints Wrote orders.json. The file contains the same structure shown in the Node.js section, with attributes listed before #text. A file that is not valid UTF-8 raises a decoding error, which the script reports as a normal error message.
In the Python output, attributes use @_ and text associated with attributes or child content is represented using #text. The force_list tuple applies to elements named item throughout the parsed document. Namespace prefixes are retained in element names because this example does not enable namespace processing. Comments are omitted by default.
Both scripts trim surrounding text whitespace using their parser settings. Their ordinary object and dictionary mappings do not use the browser converter's ordered #content representation. In particular, xmltodict joins text that is interleaved with child elements, so the original order is lost. For documents where exact node order matters, use a parser mode that explicitly preserves order or a full XML DOM or event-based transformation, and test the resulting structure. Consult each package's documentation before changing namespace or list-handling settings.
Security and performance considerations
- Do not trust XML just because it is well formed. Syntax validation does not prove that the document is safe or conforms to your business schema.
- Reject or safely handle DTDs and entities. The browser converter rejects DOCTYPE declarations. The Node.js and Python examples also reject them before parsing, and the Python example disables entity expansion as well.
- Limit input size and nesting. The browser tool enforces input, element-count and depth limits. The Node.js and Python examples also cap input at 5 MiB, 100,000 elements and a nesting depth of 128.
- Validate business rules separately. Well-formed XML is not the same as XML that conforms to an XSD schema or your application's requirements.
- Review converted values. XML comments, processing instructions, namespace prefix spelling, CDATA markers and some document-level details are not retained by this mapping.
The browser converter does not send the XML text or selected file to a conversion server. The Blogger page may still load the site's normal template resources or third-party services, depending on the site configuration. For sensitive data, use a trusted local environment and review your browser's network behavior.
XML vs JSON: what changes when you convert?
XML supports elements, attributes, namespaces, comments and mixed content. JSON, defined in RFC 8259, supports objects, arrays, strings, numbers, booleans and null. Because the models differ, conversion requires conventions for content that JSON does not represent directly.
| Feature | XML | JSON |
|---|---|---|
| Structure | Elements, attributes and text | Objects and arrays |
| Values | Character data; schemas can define application types | Strings, numbers, booleans, null, objects and arrays |
| Attributes | Built-in element attributes | Must be represented using a mapping convention |
| Comments | Supported | No native comment syntax |
| Namespaces | Supported using namespace URIs and prefixes | No native namespace model |
| Validation | DTD and XML Schema (XSD) | JSON Schema is a separate specification |
XML-to-JSON conversion is useful when an older SOAP service, RSS feed, configuration export or integration produces XML but the consuming application expects JSON. Before converting production data, decide how your application should represent attributes, namespaces, repeated elements, mixed content and data types.
Frequently asked questions
Is this XML to JSON converter free?
Yes. The browser converter is free to use and does not require an account.
Does this converter upload my XML file?
No. The conversion code reads the text in the browser and does not send it to a conversion API. The page can still load ordinary site resources or third-party services through the Blogger template, so do not use a shared or untrusted device for confidential data.
Can I convert an XML file instead of pasting XML?
Yes. Choose an XML file from your device. The browser reads it locally as UTF-8 and applies the same 2 MiB input limit as pasted XML.
Can I make every element an array?
Enable Always represent child elements as arrays. Repeated sibling elements are arrays by default; the option also wraps a single child occurrence in an array.
Why do attributes start with @?
JSON has no native attribute construct. The @ prefix distinguishes XML attributes from child-element properties. XML element names cannot begin with @, which avoids the child/attribute key collision caused by underscore-based prefixes.
How are XML namespaces represented?
Namespaced elements and attributes use expanded names containing the namespace URI, such as {urn:example}Entry. Namespace declaration attributes are omitted because the URI is included in the expanded name.
Does the converter preserve mixed-content order?
Yes. When an element interleaves meaningful text with child elements, the converter uses an ordered #content array. This preserves the sequence of those text and element nodes, but comments, processing instructions and CDATA markers are not retained.
Does it convert XML values into numbers or booleans?
No. Text and attribute values remain strings. Convert them into application-specific types only after applying the validation rules your application requires.
Can I convert JSON back to XML?
This page converts XML to JSON only. A reverse conversion is not guaranteed to reproduce the original document because XML declarations, comments, processing instructions, namespace prefix choices and other lexical details may not be represented in JSON.
Does the converter validate an XSD schema?
No. It checks whether the XML is well formed and can be parsed. It does not validate the document against an XSD, DTD or application-specific schema.
How do I check whether the output is valid JSON?
Use the Validate JSON button below the output. In JavaScript, you can also validate the output string without embedding it in a template literal:
const jsonText = document.querySelector("#cv-xml-output").value;
const data = JSON.parse(jsonText);
JSON.parse() throws a SyntaxError when the text is not valid JSON. This example reads the text directly instead of inserting arbitrary JSON into an executable template literal.
Key takeaways
- XML elements become JSON properties, and repeated sibling elements become arrays.
- Attributes use an
@prefix, while text alongside attributes uses#text. - Mixed text and child elements are stored in an ordered
#contentarray. Whitespace-only content is retained whenxml:space="preserve"applies. - Namespace-qualified names include their namespace URI so elements with different namespace identities do not collapse into the same property.
- Values remain strings; convert numbers, booleans and dates deliberately in your application.
- The browser converter rejects DTD declarations and applies practical input, element-count and nesting limits.
- Each library maps XML differently, so pick one convention and keep it consistent. XML-to-JSON conversion is a mapping, not a lossless round trip, so review it before using converted data in production.

