๐ Convert XML to JSON in JavaScript (Without External Libraries)
When youโre dealing with integrations in NetSuite or Boomi (or building a mobile app like I once did), you’ll often hit a wall:
โWhy is this API returning only XML? I just need a clean JSON object!โ
Thatโs exactly the issue I ran into โ and after testing dozens of solutions, I found a clean, developer-tested function that converts any XML DOM object into JSON โ no 3rd party library needed.
Letโs break it down โ Iโll explain how it works, common fixes, and how you can use it in real-world NetSuite or JavaScript projects.
๐ง The XML to JSON Function
Hereโs a battle-tested XML-to-JSON function that handles:
- Attributes
- Nested child elements
- Text and CDATA nodes
- Arrays (multiple same-tag children)
function xmlToJson(xml) {
var obj = {};
if (xml.nodeType === 1) { // ELEMENT_NODE
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType === 3) { // TEXT_NODE
obj = xml.nodeValue.trim();
} else if (xml.nodeType === 4) { // CDATA_SECTION_NODE
obj = xml.data;
}
// Recursively process child nodes
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
var child = xmlToJson(item);
if (child === "") continue;
if (typeof(obj[nodeName]) === "undefined") {
obj[nodeName] = child;
} else {
if (!Array.isArray(obj[nodeName])) {
obj[nodeName] = [obj[nodeName]];
}
obj[nodeName].push(child);
}
}
}
return obj;
}
โ๏ธ Example: Convert and Log XML to JSON
// Parse XML string into DOM
var xmlStr = `<person><name>David</name><age>35</age></person>`;
var xmlDoc = new DOMParser().parseFromString(xmlStr, "text/xml");
// Convert to JSON
var jsonObj = xmlToJson(xmlDoc);
console.log(JSON.stringify(jsonObj, null, 2));
Output:
{
"person": {
"name": "David",
"age": "35"
}
}
๐ ๏ธ Common Fixes for Real-World Use
Here are the most common issues developers ran into โ and how the community improved the function:
โ Fix #1: Attributes Handling
Many early versions used xml.attributes[j] โ but that caused crashes in some browsers.
โ
Fix: Use xml.attributes.item(j) for better compatibility.
โ Fix #2: Empty Text Nodes
Whitespace-only text nodes can clutter your JSON.
โ
Fix: Add trim() and skip blank nodes.
โ Fix #3: Arrays vs. Objects
When an element repeats, we need an array.
โ
Fix: Use this check:
if (!Array.isArray(obj[nodeName])) {
obj[nodeName] = [obj[nodeName]];
}
โ Fix #4: CDATA Support
Some XML includes CDATA tags.
โ
Fix: Add a check for nodeType === 4.
๐ NetSuite Use Case: Convert XML Response in SuiteScript
In SuiteScript, sometimes external REST APIs return XML instead of JSON. With this function, you can:
- Convert the XML response to a usable JSON object
- Traverse nodes easily
- Store or transform into NetSuite records
Example inside a RESTlet or Map/Reduce script:
var response = https.get({ url: myApiUrl });
var xmlDoc = xml.Parser.fromString({ text: response.body, format: xml.Parser.Type.XML });
var jsonObj = xmlToJson(xmlDoc);
๐ Related Guides on The NetSuite Pro
๐ก Final Thoughts: Keep This Function Handy
Whether youโre parsing RSS feeds, integrating 3PL data, or just cleaning up XML responses from legacy APIs โ this little xmlToJson() function is pure gold.
โ
No libraries
โ
Customizable
โ
Works in browser, Node.js, SuiteScript, or Boomi JavaScript components
Discover more from The NetSuite Pro
Subscribe to get the latest posts sent to your email.
Leave a Reply