XML to JSON Converter: how it works and how to build one
Convert XML to JSON and JSON back to XML. This guide explains what happens behind the button and shows the code, so you can build your own.
What it does
Attributes become keys that start with @ and element text becomes #text, so you can convert back without losing data. Repeated elements turn into arrays. Useful for supplier feeds, invoices, SOAP responses and old exports that only speak XML.
When to use it
- Supplier and product feeds
- SOAP API responses
- Old exports
- RSS feeds
How to use it
- Choose XML → JSON or JSON → XML.
- Paste your data or open a file.
- Copy or download the converted output.
Try it free in your browser, nothing is uploaded: https://eskillsfy.com/tools/xml-to-json
How it works
The browser has a built-in XML parser: DOMParser. It turns XML text into a tree of elements. Converting to JSON means walking that tree: each element becomes an object, attributes become keys starting with @, text becomes #text, and repeated child names become arrays.
Going back, the same rules run in reverse, so a round trip keeps your data.
Build it yourself
Here is the core of the tool. It has no dependencies unless noted, so you can paste it into any TypeScript or JavaScript project.
xmlToJson.ts (ts)
export function xmlToJson(xml: string) {
const doc = new DOMParser().parseFromString(xml, "application/xml");
const err = doc.querySelector("parsererror");
if (err) throw new Error(err.textContent ?? "Invalid XML");
const walk = (el: Element): unknown => {
const out: Record<string, unknown> = {};
for (const a of Array.from(el.attributes)) out["@" + a.name] = a.value;
for (const child of Array.from(el.children)) {
const v = walk(child);
const prev = out[child.tagName];
out[child.tagName] = prev === undefined ? v : Array.isArray(prev) ? [...prev, v] : [prev, v];
}
const text = Array.from(el.childNodes).filter((n) => n.nodeType === 3).map((n) => n.textContent).join("").trim();
if (!el.children.length && !el.attributes.length) return text;
if (text) out["#text"] = text;
return out;
};
const root = doc.documentElement;
return JSON.stringify({ [root.tagName]: walk(root) }, null, 2);
}
Make it production-ready
- Write the reverse (JSON → XML) with the same @ and #text rules.
- Escape &, < and > when writing XML text.
- Detect the direction from the file extension.
Questions
How are attributes handled?
An attribute like sku=”A1″ becomes “@sku”: “A1”. When converting back, keys that start with @ become attributes again.
Does it support namespaces?
Namespaced tags keep their prefix, for example soap:Body, so nothing is dropped.
Free, runs in your browser, nothing is uploaded.