I’m parsing an XML file with this function:
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;
}
Parsing the next file results in the below string (seen using JSON.stringify):
File (not including the ‘<‘ chars because the content is not visible then, but in my file obviously I’ve got them):
?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>
JSON:
{"playlist":{"#text":["\n","\n","\n"],"vid":[{"0":{"src":"video/intro.mp4","type":"video/mp4"}},{"0":{"src":"video/intro.mp4","type":"video/mp4"}}]}}
but I need the output to be just:
[{"0":{"src":"video/intro.mp4","type":"video/mp4"}},{"0":{"src":"video/intro.mp4","type":"video/mp4"}}]
Sorry if noob question, but I’m as new to JS as to JSON, and the days I’m with them can be counted with the fingers of one of my hands.
Thanks in advance.
EDIT: SOLVED – Solved by myself: Instead of being rude not allowing the object to be converted into a string, I’ve decided to convert it, ‘substring’ it and then reconvert the remaining string back. This is the result:
JSON.parse(JSON.stringify(jsonPlaylist).substring(44,JSON.stringify(jsonPlaylist).length-2));
Supposing that jsonPlaylist is the string var containing the whole parsed XML file.
In
php:Basically what I did was use
ltrimandrtrimto chop off what you don’t want.In
js: