# XML to JSON Converter (Free, Runs in Your Browser) > Source: https://scrape.do/tools/xml-to-json/ Free XML to JSON converter. Paste or upload XML and get JSON with options for attributes, arrays and namespaces, or turn JSON into XML. Nothing is uploaded. Paste XML or upload a file and get JSON as you type: an RSS feed, a sitemap, a SOAP response or any API export. Attributes become "@" keys and text becomes "#text", the same as Python's xmltodict, and you decide how arrays, namespaces, CDATA and numbers come out. JSON to XML works too, and nothing leaves your browser. ## How to use the XML to JSON converter 1. **Paste XML, drop a file or click Upload.** No XML at hand? Pick a sample: an RSS feed, an XML sitemap, a SOAP response or an Amazon-style product record. 2. **Read the JSON on the right.** It updates as you type. The bar under it counts the elements, lists the ones that became arrays and flags anything it had to change. 3. **Set the options** if the shape isn't what your code expects. Each one is explained below. 4. **Copy the JSON or download it** as a `.json` file. You can paste part of a document, like one product from a Google Shopping feed with its `g:` fields. Prefixes that have no `xmlns` declaration are read as declared, and the bar tells you. HTML entities that XML doesn't define, like ` ` and `—` in scraped feeds, are read as the characters they stand for. ## How XML maps to JSON **XML has elements, attributes, text, CDATA sections, comments and namespaces.** JSON has objects, arrays, strings, numbers, booleans and null. A converter needs a rule for each gap, and most of them, this one included, follow the convention of Python's xmltodict. | XML | JSON with the default options | |---|---| | `
Hi
"` | | `Hi there
`, has no clean JSON shape. The text pieces are joined into `#text` and the bar warns you, since the order of text and tags is lost. For HTML-like content, keep it as text in CDATA or convert it with the [HTML to Markdown Converter](/tools/html-to-markdown/). - **Comments and processing instructions** are left out. Tick **Keep comments** to keep comments under `#comment`. ## Numbers and booleans Every value stays a string by default, the way xmltodict does it. Converting on a guess changes data: a UPC like `0012345678905` would lose its leading zeros, and an order ID longer than 15 digits would come back with different last digits. fast-xml-parser parses numbers by default, which is why the same feed can give a different JSON in Node.js than in Python. Tick **Numbers and booleans as JSON types** when you want them typed. Only values that come back unchanged are converted: ```json {"product": {"upc": "0012345678905", "price": 49.99, "prime": true}} ``` ## Convert XML to JSON in Python [xmltodict](https://github.com/martinblech/xmltodict) gives the same JSON as this converter's defaults. Install it with `pip install xmltodict`, then: ```python import json import xmltodict with open("feed.xml", "rb") as f: data = xmltodict.parse(f, force_list=("item",)) for item in data["rss"]["channel"]["item"]: print(item["title"], item["link"]) with open("feed.json", "w", encoding="utf-8") as f: json.dump(data, f, indent=2) ``` `force_list` is the **Always an array** option. `attr_prefix` and `cdata_key` change the `@` and `#text` keys (xmltodict calls the text key `cdata_key`). To strip a namespace, map its URI to `None`: ```python data = xmltodict.parse( xml, process_namespaces=True, namespaces={"http://www.sitemaps.org/schemas/sitemap/0.9": None}, ) ``` No package at all? The standard library's ElementTree can build the same dict. This function follows the xmltodict convention and drops namespace URIs from tag names: ```python import json import xml.etree.ElementTree as ET def to_dict(elem): """An ElementTree element as a dict: @attributes, #text, lists for repeats.""" node = {f"@{name}": value for name, value in elem.attrib.items()} for child in elem: tag = child.tag.split("}")[-1] # "{http://...}creator" -> "creator" value = to_dict(child) if tag not in node: node[tag] = value elif isinstance(node[tag], list): node[tag].append(value) else: node[tag] = [node[tag], value] text = (elem.text or "").strip() if not node: return text or None if text: node["#text"] = text return node root = ET.parse("feed.xml").getroot() data = {root.tag: to_dict(root)} print(json.dumps(data, indent=2)[:500]) ``` It reads an element's own text but not the text after its children, so mixed content keeps only its first piece. ## Convert XML to JSON in Node.js [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) is the common choice in Node.js. Its defaults drop attributes and parse numbers, so set four options to get nearly the JSON this converter gives (it keeps spaces around CDATA text and joins mixed text a little differently): ```javascript import { readFileSync } from "node:fs"; import { XMLParser } from "fast-xml-parser"; const parser = new XMLParser({ ignoreAttributes: false, // keep attributes attributeNamePrefix: "@", // "@isPermaLink", like xmltodict textNodeName: "#text", parseTagValue: false, // keep "0012" as a string }); const data = parser.parse(readFileSync("feed.xml", "utf8")); console.log(JSON.stringify(data.rss.channel.item[0].guid)); ``` Install it with `npm install fast-xml-parser`. Its `isArray` option takes a function and plays the part of **Always an array**, as in the next example. ## Fetch XML at scale with Scrape.do Sitemaps, RSS feeds and XML APIs list every URL or new item in one file. At volume, sites rate-limit scripts that pull them on a schedule. The [Scrape.do API](/products/web-scraping-api/) fetches them through rotating proxies and returns the XML as the site sent it. Read a sitemap into a list of URLs: ```python import json import xml.etree.ElementTree as ET import requests TOKEN = "YOUR_TOKEN" NS = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"} response = requests.get( "https://api.scrape.do/", params={"token": TOKEN, "url": "https://www.sitemaps.org/sitemap.xml"}, timeout=60, ) response.raise_for_status() root = ET.fromstring(response.content) urls = [ { "loc": url.findtext("sm:loc", namespaces=NS), "lastmod": url.findtext("sm:lastmod", namespaces=NS), } for url in root.findall("sm:url", NS) ] print(json.dumps(urls[:2], indent=2)) ``` It prints the first two entries: ```json [ { "loc": "https://www.sitemaps.org/", "lastmod": "2016-11-21" }, { "loc": "https://www.sitemaps.org/protocol.html", "lastmod": "2022-12-15" } ] ``` Large sites split their sitemap into an index that points at child sitemaps. Fetch the index, then the children in parallel, and save every URL as JSON: ```python import json import xml.etree.ElementTree as ET from concurrent.futures import ThreadPoolExecutor import requests TOKEN = "YOUR_TOKEN" NS = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"} def fetch_xml(url): response = requests.get( "https://api.scrape.do/", params={"token": TOKEN, "url": url}, timeout=60, ) response.raise_for_status() return ET.fromstring(response.content) def urls_in(sitemap_url): root = fetch_xml(sitemap_url) return [ {"loc": u.findtext("sm:loc", namespaces=NS), "lastmod": u.findtext("sm:lastmod", namespaces=NS)} for u in root.findall("sm:url", NS) ] index = fetch_xml("https://github.blog/sitemap.xml") children = [s.findtext("sm:loc", namespaces=NS) for s in index.findall("sm:sitemap", NS)] with ThreadPoolExecutor(max_workers=5) as pool: pages = [url for batch in pool.map(urls_in, children) for url in batch] with open("urls.json", "w", encoding="utf-8") as f: json.dump(pages, f, indent=2) print(f"{len(children)} sitemaps, {len(pages)} URLs saved to urls.json") ``` Keep `max_workers` at or below your plan's concurrency limit (see the [documentation](/documentation/)). Each request in flight takes one slot, and requests over the limit are queued or rejected until a slot opens; the free plan allows 5 at a time, which is why the example uses 5. Sitemaps that end in `.xml.gz` are usually gzip files: when the body starts with the gzip bytes (`b"\x1f\x8b"`), pass `gzip.decompress(response.content)` to the parser instead. Some servers, the New York Times among them, send plain XML at a `.xml.gz` address. Scrape.do returns response bodies up to 4 MB, as listed under [output and response](/documentation/api-response/response-output/), which covers most single sitemaps and feeds. The same pattern in Node.js turns an RSS feed into clean JSON items: ```javascript import { XMLParser } from "fast-xml-parser"; const params = new URLSearchParams({ token: "YOUR_TOKEN", url: "https://github.blog/feed/", }); const response = await fetch(`https://api.scrape.do/?${params}`); const xml = await response.text(); const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: "@", textNodeName: "#text", parseTagValue: false, isArray: (name) => name === "item" || name === "category", }); const feed = parser.parse(xml); const items = feed.rss.channel.item.map((item) => ({ title: item.title, link: item.link, published: new Date(item.pubDate).toISOString(), categories: item.category ?? [], })); console.log(JSON.stringify(items.slice(0, 2), null, 2)); ``` Save it as a `.mjs` file so the top-level `await` works. Each item comes out with its title, link, an ISO date and its list of categories. Replace `YOUR_TOKEN` with your API token; signing up gets you 1,000 free credits a month, no card needed. ## JSON to XML Switch the tool to **JSON to XML** to go the other way with the same keys. This JSON: ```json { "product": { "@id": "B0EXAMPLE1", "title": "Example Audio Wireless Earbuds", "price": { "@currency": "USD", "#text": "49.99" }, "feature": ["Noise cancelling", "30h battery"], "coupon": null } } ``` becomes this XML: ```xml