Guide
Turning XML documents into JSON
By Logappradeep · ServiceNow developer
Plenty of data still arrives as XML: SOAP responses, RSS and Atom feeds, sitemaps, Maven POM files, and exports from older business systems. JavaScript and most modern APIs prefer JSON, so converting XML to JSON is a common first step before filtering, transforming, or loading the data elsewhere.
XML has features JSON lacks
XML distinguishes between attributes and child elements, allows mixed content (text interleaved with tags), and supports comments, CDATA sections, processing instructions, and namespaces. JSON has only objects, arrays, strings, numbers, booleans, and null. A converter therefore needs conventions for information that has no native JSON equivalent. This tool keeps the output as compact as possible:
- Attributes become keys prefixed with
@, such as"@id": "7". - Elements that contain only text become plain string values.
- Elements with attributes and text keep the text under a
#textkey. - Repeated elements are grouped into an array.
- CDATA sections are merged into the element's text, and empty elements become
null. - Comments, processing instructions, and the XML declaration are dropped, since they rarely matter to the data.
So this input:
<user id="7"><name>Ada</name><tag>a</tag><tag>b</tag><p lang="en">Hi</p></user>
becomes:
{
"user": {
"@id": "7",
"name": "Ada",
"tag": ["a", "b"],
"p": { "@lang": "en", "#text": "Hi" }
}
}
Gotchas when consuming the output
- Single versus repeated elements. One
<tag>becomes a string or object, while two or more become an array. Code that reads the result should normalize both shapes, or a feed with one item will break a loop written for many. - Shapes change when attributes appear.
<p>Hi</p>yields"Hi", but<p lang="en">Hi</p>yields an object with#text. Handle both if attributes are optional in your source. - Everything is a string.
<age>36</age>yields"36", not the number 36, because XML text carries no type information. Convert values explicitly in your code. - Namespace prefixes stay in names, so
soap:Bodybecomes a key with a colon in it. Access it with bracket notation. - Malformed XML fails entirely. Unclosed tags, an unescaped
&in text, or mismatched case (<Item>...</item>) stop the conversion, and the error panel shows the parser message.
Typical uses include inspecting a SOAP response while building an integration, turning a sitemap or RSS feed into data for a script, and creating JSON fixtures from XML samples supplied by a partner. The XML is parsed live in your browser, so internal documents never leave your device.