1:00 0 0
Convertir XML en JSON con JAVASCRIPT

Convertir XML en JSON con JAVASCRIPT

  DrUalcman |  diciembre 142017

Una autentica locura.

Realmente muchas veces es "difícil" encontrar una solución fácil a tus problemas, ya que algunos programadores se complican demasiado la vida. En esta ocasión os traigo una modificación del mejor de los scripts que he encontrado para pasar de XML a JSON con JAVASCRIPT.

Mi modificación

Como ya sabéis, intento utilizar lo menos posible JQUERY en mis scripts, sobre todo para no sobrecargar mucho de librerías las pagina, pero en este caso este script requiere de JQERY 1.9+. Yo he intentado simplificar el script original, no se el autor pero os dejo el link como siempre para que podáis ver como es el original y si os interesa mas usar ese, pues lo usais.

        function xml2json(xml) {
if (!xml) return {}; // quick fail

//### PARSER LIBRARY
// Core function
function parseXML(node, simple) {
if (!node) return null;
var txt = '', obj = null, att = null;
var nt = node.nodeType, nn = jsVar(node.localName || node.nodeName);
var nv = node.text || node.nodeValue || '';
if (node.childNodes) {
if (node.childNodes.length > 0) {
$.each(node.childNodes, function (n, cn) {
var cnt = cn.nodeType, cnn = jsVar(cn.localName || cn.nodeName);
var cnv = cn.text || cn.nodeValue || '';
if (cnt == 8) {
return; // ignore comment node
}
else if (cnt == 3 || cnt == 4 || !cnn) {
// ignore white-space in between tags
if (cnv.match(/^\s+$/)) {
return;
};
txt += cnv.replace(/^\s+/, '').replace(/\s+$/, '');
// make sure we ditch trailing spaces from markup
}
else {
obj = obj || {};
if (obj[cnn]) {
// http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
if (!obj[cnn].length) obj[cnn] = myArr(obj[cnn]);
obj[cnn] = myArr(obj[cnn]);

obj[cnn][obj[cnn].length] = parseXML(cn, true);
obj[cnn].length = obj[cnn].length;
}
else {
obj[cnn] = parseXML(cn);
};
};
});
};//node.childNodes.length>0
};//node.childNodes

if (obj) {
obj = $.extend((txt != '' ? new String(txt) : {}), obj || {});
txt = (obj.text) ? ([obj.text || '']).concat([txt]) : txt;
if (txt) obj.text = txt;
txt = '';
};
var out = obj || txt;
return out;
};// parseXML
// Core Function End
// Utility functions
var jsVar = function (s) { return String(s || '').replace(/-/g, "_"); };

var myArr = function (o) {

// http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
if (!$.isArray(o)) o = [o]; o.length = o.length;

// here is where you can attach additional functionality, such as searching and sorting...
return o;
};
// Utility functions End
//### PARSER LIBRARY END

// Convert plain text to xml
if (typeof xml == 'string') xml = text2xml(xml);

// Quick fail if not xml (or if this is a node)
if (!xml.nodeType) return;
if (xml.nodeType == 3 || xml.nodeType == 4) return xml.nodeValue;

// Find xml root node
var root = (xml.nodeType == 9) ? xml.documentElement : xml;

// Convert xml to json
var out = parseXML(root, true /* simple */);

// Clean-up memory
xml = null; root = null;

// Send output
return out;

// scripts de ayuda

function text2xml(str) {
// NOTE: jQuery makes all tags uppercase
/* jquery 1.9+ */
return $.parseXML(str);
}

// NEW isNum function: 01/09/2010
// Thanks to Emile Grau, GigaTecnologies S.L., www.gigatransfer.com, www.mygigamail.com
function isNum(s) {
// based on utility function isNum from xml2json plugin (http://www.fyneworks.com/ - diego@fyneworks.com)
// few bugs corrected from original function :
// - syntax error : regexp.test(string) instead of string.test(reg)
// - regexp modified to accept comma as decimal mark (latin syntax : 25,24 )
// - regexp modified to reject if no number before decimal mark : ".7" is not accepted
// - string is "trimmed", allowing to accept space at the beginning and end of string
var regexp = /^((-)?([0-9]+)(([\.\,]{0,1})([0-9]+))?$)/
return (typeof s == "number") || regexp.test(String((s && typeof s == "string") ? s.trim() : ''));
};
}

En mi versión devuelvo directamente un objeto JSON solo con el contenido de los datos del XML. En la versión original, ademas, incluye las propiedades.

Ejemplo de retorno
JSON Object {[tipo dato]:[dato]}

Créditos y documentación

Aunque no he conseguido encontrar el nombre completo del autor original del script, creo que se llama Diego y licencio el script bajo http://en.wikipedia.org/wiki/MIT_License por lo que esta licencia se mantiene. Inicialmente el lo creo como extensión del JQUERY pero yo lo he simplificado a una simple función.

Ademas os incluyo en los links, documentación sobre como hacer esto, y otro script que me parece algo mas complicado de entender, de hecho no conseguí codificarlo a mi gusto para que devolviera solo los datos.


Happy codding!!!


#javascript #jquery #xml #datos #utilidades

0 Guest reviews

 
 
 

File