How to convert XML to JSON
- Paste or open the XML. You can drop a file onto the input box. The converter accepts any well-formed XML document: API responses, RSS and Atom feeds, SOAP envelopes, Maven and .NET config files, SVG, sitemaps and exports from other systems.
- Check the JSON. It updates as you type. If the XML is not well-formed, the box below the buttons gives the line, the column and the parser's message, with the line itself shown.
- Adjust the mapping if the consumer of the JSON expects a particular convention, for example
_instead of@for attributes, or a field that is always an array. Then copy the JSON, download it, or press Swap to send it to the JSON to XML converter.
Worked example: XML to JSON and back
This order uses all the features that cause trouble: an attribute, an element with both an attribute and text, a repeated element, a namespace prefix, CDATA and an ID too long for a JavaScript number.
<order id="A-1001" xmlns:inv="urn:example:inventory">
<ref>1453729827150749696</ref>
<total currency="EUR">42.50</total>
<line sku="PEN"><qty>2</qty></line>
<line sku="INK"><qty>1</qty></line>
<inv:warehouse>Pune</inv:warehouse>
<note><![CDATA[Leave at door & ring <twice>]]></note>
</order>
With the default settings it becomes:
{
"order": {
"@xmlns:inv": "urn:example:inventory",
"@id": "A-1001",
"ref": 1453729827150749696,
"total": { "@currency": "EUR", "#text": 42.50 },
"line": [
{ "@sku": "PEN", "qty": 2 },
{ "@sku": "INK", "qty": 1 }
],
"inv:warehouse": "Pune",
"note": "Leave at door & ring <twice>"
}
}
Note the details. ref keeps all 19 digits. Most online converters print 1453729827150749700, because they pass the value through a JavaScript number. 42.50 keeps its trailing zero. The two line elements became an array, and the CDATA was unwrapped into a normal string. Press Swap and the JSON to XML converter rebuilds the same elements and attributes. CDATA comes back as escaped text (&, <) unless you turn its CDATA option on. Both forms mean the same thing to an XML parser.
XML to JSON mapping conventions
XML and JSON do not model data the same way. XML has attributes, mixed content, namespaces and document order. JSON has arrays and types. Every converter has to choose a convention, and these are the choices made here. They match the widely used xmltodict and Newtonsoft (Json.NET) conventions.
| XML | JSON | Notes |
|---|---|---|
<a>x</a> | "a": "x" | Text-only elements become plain values |
<a id="1"/> | "a": {"@id": 1} | Prefix configurable: @, _, - or none |
<a id="1">x</a> | {"@id": 1, "#text": "x"} | Text moves under the text key when attributes exist |
<b>1</b><b>2</b> | "b": [1, 2] | Only when repeated, unless forced (see below) |
<a/> or <a></a> | "a": null | Empty elements |
<ns:a xmlns:ns="..."> | "ns:a", "@xmlns:ns" | Or "a" with strip prefixes (lossy: two namespaces can collide) |
<![CDATA[<b>]]> | "<b>" or {"#cdata": "<b>"} | CDATA is only an escaping style. Merging it into text loses nothing a parser can see |
<p>Hi <b>you</b> there</p> | {"b": "you", "#text": "Hi there"} | Lossy. Mixed content loses the position of the text between child elements |
<!-- note --> | dropped, or "#comment" | Untick Ignore comments to keep them |
<?xml ... ?>, <!DOCTYPE>, processing instructions | dropped | They describe the file, not the data |
<a>1</a><b/><a>2</a> | {"a": [1, 2], "b": null} | Lossy. The order of interleaved siblings is not kept |
The single-item array problem
XML has no array type. A converter can only tell that something is a list when the tag appears twice. If an order has one <line>, you get "line": {...}. If it has two, you get "line": [...]. Code that loops over order.line then breaks on single-line orders. There are two fixes: type the repeating tag names into Force arrays (comma separated), or set Repeated elements to always array so that every child element is wrapped in an array. Libraries have the same switch. In xmltodict it is called force_list, in fast-xml-parser isArray, and in Json.NET the json:Array="true" attribute.
Types: strings, numbers and booleans
In XML everything is text unless a schema says otherwise. With Infer numbers & booleans on, values that are valid JSON numbers (42, -3.5, 1e6) and the words true and false become JSON numbers and booleans. Values that only look numeric stay strings: 00742 (a ZIP code), +44, 1,000 and 0x1F. Inferred numbers are written using the original characters, so a 64-bit ID or a 30-digit decimal is never rounded. If a downstream system needs strings, for example because an ID happens to be all digits, untick the option.
Convert XML to JSON in code
Python (xmltodict)
import json, xmltodict # pip install xmltodict
with open("order.xml", "rb") as f:
data = xmltodict.parse(f, force_list=("line",)) # attr_prefix="@", cdata_key="#text"
print(json.dumps(data, indent=2))
xmltodict uses the same @ and #text conventions as this page and keeps every value as a string. To go back, use xmltodict.unparse(data, pretty=True).
JavaScript / Node.js (fast-xml-parser)
import { XMLParser } from "fast-xml-parser";
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: "@",
textNodeName: "#text",
parseTagValue: false, // keep long IDs as strings
isArray: (name) => name === "line",
});
const json = JSON.stringify(parser.parse(xml), null, 2);
Attributes are ignored by default, so ignoreAttributes: false is the setting people usually miss. In the browser, new DOMParser().parseFromString(xml, "application/xml") gives you a DOM to walk yourself, which is what this page does.
Java (Jackson XmlMapper or org.json)
// Jackson 2.12+ (jackson-dataformat-xml): repeated elements become arrays
JsonNode node = new XmlMapper().readTree(xml.getBytes(StandardCharsets.UTF_8));
String json = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(node);
// org.json: attributes become plain keys, text next to attributes goes to "content"
JSONObject obj = XML.toJSONObject(xml, true); // true = keep values as strings
String json2 = obj.toString(2);
C# (Json.NET)
var doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc, Formatting.Indented, omitRootObject: false);
// attributes => "@name", text => "#text", CDATA => "#cdata-section"
Command line (yq, xq)
# mikefarah/yq v4
yq -p xml -o json order.xml
# match this page's conventions
yq -p xml -o json --xml-attribute-prefix @ --xml-content-name '#text' order.xml
# xq (from the Python "yq" package, uses xmltodict) piped into jq syntax
xq '.order.line' order.xml
n8n
In n8n, the XML node has a Mode of XML to JSON. It uses the xml2js library, which puts attributes under a $ key and text under _ instead of @ and #text. Its Explicit Array option is the same as always array here. If you want to see what a payload will look like before you build the workflow, paste a sample here and pick the matching options.
Fixing XML parse errors
Browsers parse XML strictly. One error stops the whole document, and the converter shows where it is. The usual causes are:
- Unescaped
&or<in text. Write&and<, or wrap the text in<![CDATA[ ... ]]>. - HTML entities. XML defines only
& < > " '. Replace with and©with©. - More than one root element. Wrap the fragments in a single parent such as
<items>...</items>. - Mismatched or unclosed tags. XML is case-sensitive, so
<Item>...</item>is an error. The XML validator and XML beautifier make these easy to spot.
Frequently asked questions
How do I convert XML to JSON?
Paste your XML or open an .xml file above. The JSON appears as you type. Each element becomes a key, attributes become keys starting with @, repeated elements become arrays, and text next to attributes goes under #text. Copy the result or download it as a .json file. Nothing is uploaded.
Why is one element an object in one record and an array in another?
XML has no array type, so a converter only knows a list exists when it sees the same tag twice. A book with one tag gives "tag": "x" and a book with two gives "tag": ["x", "y"]. To get a stable shape, list the tag names under Force arrays, or switch Repeated elements to Always array.
Are numbers and booleans converted, and are long IDs safe?
With Infer numbers and booleans on, text such as 42, 9.99 and true becomes a JSON number or boolean. The digits are copied exactly as written, so an ID like 1453729827150749696 is not rounded. Values with leading zeros, such as 00742, stay strings. Turn the option off to keep every value as a string.
What happens to XML namespaces?
By default the prefix stays in the key, so dc:title becomes "dc:title" and xmlns declarations become @xmlns attributes. Choose Strip prefixes to get plain keys like "title" and drop the xmlns attributes. Stripping is convenient but loses information if two namespaces use the same local name.
Can I convert the JSON back to the same XML?
Yes, if the XML has no mixed content. Use the swap button to send the result to the JSON to XML converter, which reads the same @ and #text conventions. Comments, processing instructions, the order of interleaved siblings and text mixed between child elements are not preserved.
Why does my XML show a parse error?
The browser's XML parser is strict. Common causes are a missing closing tag, an unescaped & in text (write &), HTML entities such as that XML does not define (use  ), more than one root element, or whitespace before the <?xml ?> declaration. The error box shows the line and column.
Is my XML uploaded to a server?
No. Parsing uses the DOMParser built into your browser, and the JSON is built by JavaScript on this page. The XML never leaves your device.