Currently, I am utilizing the following function to parse an XML file:
function xmlToJson(xml) {
var attr, child, attrs = xml.attributes,
children = xml.childNodes,
key = xml.nodeType,
obj = {},
i = -1,
o = 0;
if (key == 1 && attrs.length) {
obj[key = o] = {};
while (attr = attrs.item(++i)) {
obj[key][attr.nodeName] = attr.nodeValue;
}
i = -1;
} else if (key == 3) {
obj = xml.nodeValue;
}
while (child = children.item(++i)) {
key = child.nodeName;
if (obj.hasOwnProperty(key)) {
if (obj.toString.call(obj[key]) != '[object Array]') {
obj[key] = [obj[key]];
}
obj[key].push(xmlToJson(child));
} else {
obj[key] = xmlToJson(child);
}
}
return obj;
}
After parsing the next file, the resulting string (displayed using JSON.stringify) is as follows:
File (omitting the '<' characters as they are not visible, but they are present in the actual file):
?xml version="1.0" encoding="UTF-8" standalone="no"?>
playlist>
vid src="video/intro.mp4" type="video/mp4"/>
vid src="video/intro.mp4" type="video/mp4"/>
/playlist>
Converted to JSON:
{"playlist":{"#text":["\n","\n","\n"],"vid":[{"0":{"src":"video/intro.mp4","type":"video/mp4"}},{"0":{"src":"video/intro.mp4","type":"video/mp4"}}]}}
However, I require the output to be simplified to:
[{"0":{"src":"video/intro.mp4","type":"video/mp4"}},{"0":{"src":"video/intro.mp4","type":"video/mp4"}}]
Apologies for the novice question, as I am new to both JS and JSON, and my experience with them can be counted on one hand.
Thank you in advance.
EDIT: RESOLVED - I resolved the issue by allowing the object to be converted into a string, then using 'substring' to extract the necessary part, and finally converting the remaining string back. Here is the solution:
JSON.parse(JSON.stringify(jsonPlaylist).substring(44,JSON.stringify(jsonPlaylist).length-2));
Assuming jsonPlaylist
is the string variable containing the entire parsed XML file.