# 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` | `"title": "Hi"` | | `9.99` | `"price": {"@currency": "USD", ...}` | | `ab` | `"tag": ["a", "b"]` | | `` | `"coupon": null` | | `Hi

]]>
` | `"d": "

Hi

"` | | `9.99` | `"g:price": "9.99"` | | `` | Left out | The price row in full, since attributes and text sit side by side: ```json { "price": { "@currency": "USD", "#text": "9.99" } } ``` The root element stays as the top key, so an RSS feed starts with `{"rss": ...}` and a sitemap with `{"urlset": ...}`. Whitespace between elements is indentation and is dropped; text inside an element is trimmed unless you untick **Trim text**. ## XML to JSON conventions compared There is no standard for this mapping, so libraries disagree. If your code already uses one of them, match its keys: | Library | Attributes | Element text | Repeated elements | Values | |---|---|---|---|---| | This converter (default) | `@name` | `#text` | Array when repeated | Strings | | xmltodict (Python) | `@name` | `#text` | Array when repeated | Strings | | fast-xml-parser (Node.js) | Dropped by default | `#text` | Array when repeated | Numbers and booleans parsed | | xml2js (Node.js) | `$` object | `_` | Always arrays | Strings | | xml-js, compact mode | `_attributes` object | `_text` | Array when repeated | Strings | To match fast-xml-parser with attributes on, set the attribute prefix to `@_`. For xml-js, pick **_attributes object** and set the text key to `_text`. For xml2js, set **Arrays** to **Always**, the text key to `_`, and group attributes under `$`. ## Arrays: when repeated or always **This is the option that breaks scrapers most often.** The same feed gives a different shape depending on how many items it has that day: ```json {"rss": {"channel": {"item": {"title": "One"}}}} ``` ```json {"rss": {"channel": {"item": [{"title": "One"}]}}} ``` The first is one item with **When repeated**; the second is the same file with `item` in **Always an array**. Code written for the second fails on the first with a key or type error. Pin the elements your code loops over (`item` for RSS, `url` for sitemaps, `entry` for Atom), or set **Arrays** to **Always** to make every child an array. The bar under the output lists the elements that repeat in your file, and one click adds any of them to the list. ## Namespaces: keep, strip or expand Feeds and APIs mix vocabularies through namespaces: `g:` for Google Shopping fields, `dc:` for Dublin Core, `soap:` for SOAP envelopes. Take this Google Shopping entry: ```xml 49.99 USD ``` | Namespaces option | Key for the price | |---|---| | Keep prefixes (default) | `g:price` | | Strip prefixes | `price` | | Full namespace URI | The URI, a colon, then `price` | **Keep prefixes** also keeps the `xmlns` declarations as `@xmlns:g` keys, the way xmltodict does. **Strip prefixes** gives the shortest keys and drops the declarations; if two namespaces use the same local name under one parent, they merge into one array and the bar warns you. **Full namespace URI** matches xmltodict's `process_namespaces=True` and is safe when prefixes change from file to file. ## CDATA, entities, empty elements and mixed content - **CDATA** holds text the parser must not read as markup, usually HTML inside an RSS ``. By default it becomes part of the element's text. Pick **Own key (#cdata)** to keep it apart. - **Entities** like `&` and `©` are decoded, so the JSON holds `&` and `©`. Entities declared in the file's DOCTYPE are expanded too. - **Empty elements** like `` become `null`, or an empty string if you pick that under **Empty elements**. - **Mixed content**, text and tags inside one element like `

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 Example Audio Wireless Earbuds 49.99 Noise cancelling 30h battery ``` Keys that aren't valid XML names, like `first name` or `2x`, are rewritten (`first_name`, `_2x`) and listed under the output. `#cdata` keys become CDATA sections, and `&` and `<` in values are escaped. In Python, `xmltodict.unparse(data, pretty=True)` does the same. ## Related reading - [XPath and CSS Selector Tester](/tools/xpath-css-tester/), to pull a few values out of an XML file instead of converting all of it - [8 Types of Data Extracted with Web Scraping](/blog/web-scraping-data-types/), from HTML tables to JSON and XML APIs - [How to Find and Read robots.txt](/blog/robots-txt/), where sites point to their sitemaps - [Sitemap Finder](/tools/sitemap-finder/), to find a site's sitemap and list its URLs before you convert it - [Building a Python Web Crawler from Scratch](/blog/web-crawler-python/), for the pages your sitemap lists - [HTML to Markdown Converter](/tools/html-to-markdown/), for the HTML inside feed descriptions - [More free tools](/tools/) for scraping work, from HAR files to user agents ## FAQ ### How do I convert XML to JSON? Paste the XML in the box above, drop a file on it or click **Upload**. The JSON shows up on the right as you type; copy it, or download it as a `.json` file. In code, Python's xmltodict and Node's fast-xml-parser do the same in one call, and the examples below show both. ### Is my XML uploaded anywhere? No. Your browser's built-in XML parser reads it and JavaScript in the tab converts it, so the tool sends nothing anywhere. Session recording is masked on the converter too, since API responses and exports often carry private data. ### Why is an element sometimes an array and sometimes an object? XML has no arrays, so a converter only sees repeats. With **When repeated**, a feed with two `` elements gives an array, and a feed with one gives a single object, which breaks code that loops over it. Type the name in **Always an array**, or set **Arrays** to **Always**, and the shape stays the same for every file. ### What happens to XML attributes? They become keys with an `@` in front, next to the element's children, and the element's own text moves to `#text`. So a price with a currency attribute turns into an object with `@currency` and `#text`. You can change the prefix, group attributes under `_attributes`, or drop them. ### Why are numbers still strings in the JSON? XML text has no types, and guessing changes data: `00123` would become 123, and a 20-digit ID would lose its last digits. Tick **Numbers and booleans as JSON types** to convert the values that survive the trip, while leading zeros, long IDs and exponents stay strings. ### Can it convert JSON back to XML? Yes. Switch to **JSON to XML**. Keys starting with `@` become attributes, `#text` becomes the element text, arrays become repeated elements, and JSON with several top-level keys is wrapped in a `` element. ### How big a file can it convert? Uploads go up to 50 MB. Files over 1 MB convert when you press **Convert**, and the output box shows the first megabyte while **Copy** and **Download** get all of it. For files bigger than that, stream them in code with ElementTree's `iterparse` instead of loading the whole tree.