Skip to content
Browse files

added option 'log' for error messages

  • Loading branch information...
1 parent 19a7228 commit 455e88a551fc9be632a2e3bc7659aae04c5f2822 @derderderist committed Jun 7, 2011
Showing with 19 additions and 7 deletions.
  1. +6 −4 README.markdown
  2. +12 −2 lib/jquery.xmltojson.js
  3. +1 −1 lib/jquery.xmltojson.min.js
View
10 README.markdown
@@ -34,6 +34,7 @@ XMLtoJSON requires:
detectTypes // Automatically parse true, false, integer and null values
filter // Define a function to customize each XML attribute or text value
fallback // Define a function if XML is invalid or could not requested
+ log // Enable or disable output on console for errors and converting problems
See examples/index.html to get a full overview of all parameters in usage
@@ -51,7 +52,7 @@ See examples/index.html to get a full overview of all parameters in usage
The XML is fully converted in a JSON object and accessed by default object connection.
- data.json.rootnode.subnode // Return object <rootnode>
+ data.json.rootnode // Return object <rootnode>
data.json.rootnode.subnode // Return object <subnode> in <rootnode>
data.json.rootnode.subnode[0] // Return first <subnode> in <rootnode>
data.json.rootnode._version // Return attribute 'version' for <rootnode>
@@ -65,7 +66,7 @@ You can use a string notation (like 'rootnode.subnode') to do something with the
data.createNodes(<String> path) // create a full JSON tree by the given path
data.remove(<String> path) // remove the given path from the JSON object
- data.find(<String> path, [<String> conditions]) // Powerful method to get a specific part of the JSON object. See examples/index.html to get further information.
+ data.find(<String> path, [<String> conditions]) // Method to get a specific part of the JSON object. See examples/index.html to get further information.
## Browser compatibility
@@ -74,10 +75,11 @@ XMLtoJSON was successfully tested in:
* Internet Explorer 6/7/8/9 (Windows)
* Firefox 4.0.1 (Windows)
-* Google Chrome 10.0.648.204 (Windows)[Start with --allow-file-access-from-files or run demo from a webserver]
+* Google Chrome 10.0.648.204 (Windows)
* Safari 5.0.5 (Windows)
-* Opera 11.10 (Windows)[Run demo from a webserver]
+* Opera 11.10 (Windows)
+Note: Chrome and Opera do not allow access via a Ajax-Request to a file from locale storage. Run the demo from a webserver or configure your browser (e.g. --allow-file-access-from-files for Chrome)
## ToDo
View
14 lib/jquery.xmltojson.js
@@ -23,6 +23,7 @@
* detectTypes: Convert true, false, integer or null values
* filter: Add miscellaneous filter function to parse the XML attribute/node values (e.g. filter: function(value){return value + '!'})
* fallback: Function which is thrown if the XML is invalid or could not requested
+ * log: Enable or disable output on console for errors and converting problems
*/
var XMLtoJSON = Class.extend({
@@ -48,7 +49,8 @@ var XMLtoJSON = Class.extend({
cache: false,
detectTypes: false,
filter: null,
- fallback: null
+ fallback: null,
+ log: false
}, options);
// Get XML as string
@@ -493,7 +495,15 @@ var XMLtoJSON = Class.extend({
// Log specific error message
throwError: function(msg){
- if(typeof console != 'undefined') console.log(msg);
+ if(this.options.log){
+ if(!window.console){
+ // Add log method to window.console
+ window.console = {
+ log : function(s){ alert(s); }
+ };
+ }
+ console.log(msg);
+ }
}
});
View
2 lib/jquery.xmltojson.min.js
@@ -1 +1 @@
-var XMLtoJSON=Class.extend({init:function(a){this.xml=false,this.document=false;this.json={};this.duration=new Date();this.options=$.extend({url:false,xmlString:false,namespaces:false,valueIdentifier:"$",attributeIdentifier:"_",emptyValuesAsNull:false,modify:{},clearEmptyNodes:false,cache:false,detectTypes:false,filter:null,fallback:null},a);if(this.options.url){this.receiveXML()}if(this.options.xmlString){this.xml=this.options.xmlString}if(this.xml){this.parseXML();this.convertXML();if(this.options.fallback!=null&&(this.json=={}||this.json.parsererror)){this.options.fallback({message:"XML is invalid",code:500})}this.modifyJSON()}this.duration=new Date()-this.duration+" ms"},receiveXML:function(){var b=this.options.url,a;$.ajax({type:"GET",url:b,async:false,dataType:"text",cache:this.options.cache,complete:function(c){if(c.responseText){a=c.responseText.replace(/^\s+/,"")}}});if(a){this.xml=a}else{this.throwError("Cannot receive XML from "+this.options.url);if(this.options.fallback!=null){this.options.fallback({message:"Cannot receive XML from "+this.options.url,code:404})}}},parseXML:function(){this.xml=this.xml.replace(/^[\s\n\r\t]*[<][\?][xml][^<^>]*[\?][>]/,"");if(window.ActiveXObject){this.document=new ActiveXObject("Microsoft.XMLDOM");this.document.async=false;this.document.loadXML(this.xml)}else{this.document=new DOMParser();this.document=this.document.parseFromString(this.xml,"application/xml")}if(!this.xml||!this.document){this.throwError("Cannot parse XML")}},convertXML:function(){var b=this;(function a(d,h,n,j){var f=n.valueIdentifier,m=n.attributeIdentifier;if(d.nodeType===9){$.each(d.childNodes,function(){a(this,h,n,j)})}else{if(d.nodeType===1){var g=j[f]?{valueIdentifier:true}:{};var k=d.nodeName;var c=n.namespaces==true?true:false;var i={};if(k.indexOf(":")!=-1){g[k.substr(0,k.indexOf(":"))]=true}$.each(d.attributes,function(){var o=this.nodeName;var p=this.nodeValue;if(b.options.filter){p=b.options.filter(p)}if(b.options.detectTypes){p=b.detectTypes(p)}if(o==="xmlns"){j[f]=p;g[f]=true}else{if(o.indexOf("xmlns:")===0){j[o.substr(o.indexOf(":")+1)]=p}else{if(o.indexOf(":")!=-1){i[m+o]=p;g[o.substr(0,o.indexOf(":"))]=true}else{if(b.options.emptyValuesAsNull&&(p===""||p===null)){i[m+o]=null}else{i[m+o]=p}}}}});var e=c?j:g;$.each(e,function(o,p){if(e.hasOwnProperty(o)){i[m+"xmlns"]=i[m+"xmlns"]||{};i[m+"xmlns"][o]=p}});if(h[k] instanceof Array){h[k].push(i)}else{if(h[k] instanceof Object){h[k]=[h[k],i]}else{h[k]=i}}if(b.options.emptyValuesAsNull&&d.childNodes.length==0){h[k]=null}$.each(d.childNodes,function(){a(this,i,n,j)})}else{if(d.nodeType===3){var l=d.nodeValue;if(!l.match(/[\S]+/)){return}if(b.options.filter){l=b.options.filter(l)}if(b.options.detectTypes){l=b.detectTypes(l)}if(h[f] instanceof Array){h[f].push(l)}else{if(h[f] instanceof Object){h[f]=[h[f],l]}else{h[f]=l}}}}}})(this.document,this.json,this.options,{})},modifyJSON:function(){var _this=this,attributeIdentifier=this.options.attributeIdentifier;$.each(this.options.modify,function(url,modified){var all=url.match(/\.\*$/)?true:false;var url=all?url.replace(/\.\*$/,""):url;var content=_this.find(url);if(content){var newParent=modified.replace(/\.[^\.]*$/,"");if(modified.split(".").length>1){var newNode=newParent+'["'+modified.split(".")[modified.split(".").length-1]+'"]'}else{var newNode=modified}if(!all){_this.remove(url)}if(newParent.split(".").length>1){_this.createNodes(newParent)}_this.createNodes(modified);if(all){newNode=newNode.match(/\[\"\"\]/)?"":(newNode+".");$.each(content,function(key,value){if(key[0]!=attributeIdentifier){eval("_this.json."+newNode+key+" = value")}});$.each(_this.find(url),function(key,value){if(key[0]!=attributeIdentifier){_this.remove(url+"."+key)}})}else{eval("_this.json."+newNode+" = content")}if(_this.options.clearEmptyNodes){var parentNode=all?_this.find(url):_this.find(url.replace(/\.[^\.]*$/,""));var emptyNodes=true;$.each(parentNode,function(key,value){if(value instanceof Object){var children=0;for(var i in value){children++}if(children>1||children==1&&!_this.options.namespaces){return emptyNodes=false}}if(key[0]!=attributeIdentifier){return emptyNodes=false}});if(emptyNodes){all?_this.remove(url):_this.remove(url.replace(/\.[^\.]*$/,""))}}}})},createNodes:function(string){var _this=this;var node=this.get(string,false);if(node){return}(function checkNode(url,index){var current=url.split(".")[index];if(!current){return}var partUrl=[];for(var i=0;i<=index;i++){partUrl.push(url.split(".")[i])}partUrl=partUrl.join(".");var part=_this.get(partUrl,false);if(!part){eval("_this.json."+partUrl+"={}")}checkNode(url,index+1)})(string,0)},get:function(path,log){var array="",root=null,log=(log==false)?false:true;path=path.replace(/^\./,"");$.each(path.split("."),function(){if(this.match(/\[*.\]$/)){array+='["'+this.split("[")[0]+'"]'+this.match(/\[*.\]$/)[0]}else{array+='["'+this+'"]'}});try{root=eval("this.json"+array)}catch(e){if(log==true){this.throwError("Invalid path "+path)}}return(root)?root:(log==true?this.throwError("Could not access "+path):null)},find:function(path,condition){var _this=this,parts=[];function children(root,path){var url="",parts=[];$.each(path.split("."),function(i){var tempParts=[];if(i==0){url=this;tempParts=root}else{url+="."+this;if(this.match(/\[*.\]$/)){tempParts=parts[this.split("[")[0]][this.match(/\[*.\]$/)[0].replace(/[\[|\]]/g,"")]}else{if(parts instanceof Array){var part=this;$.each(parts,function(){if(this instanceof Array){$.each(this,function(){if(this[part]!=undefined){tempParts.push(this[part])}})}else{if(this[part]!=undefined){tempParts.push(this[part])}}})}else{tempParts=parts[this]}}}if(!tempParts||tempParts.length==0){_this.throwError("Invalid path "+url);parts=[];return false}else{parts=tempParts}});return parts}if(path.split(".")[0].match(/\[*.\]$/)){var index=path.split(".")[0].match(/\[*.\]$/)[0].replace(/[\[|\]]/g,"");var root=this.json[path.split(".")[0].replace(/\[.*\]/,"")][index]}else{var root=this.json[path.split(".")[0]]}parts=children(root,path);if(condition){function match(element,operator,rule){if(element&&operator&&rule){if(operator==="=~"){var options="";if(rule.match(/^\/.*/)&&rule.match(/\/.$/)){options=rule[rule.length-1];rule=rule.substring(0,rule.length-1)}rule=rule.replace(/^\//,"").replace(/\/$/,"");return(element.toString().match(new RegExp(rule,options)))?true:false}else{if(operator==="=="||operator==="!="){return(eval("element.toString()"+operator+"rule"))?true:false}else{rule=parseInt(rule);element=parseInt(element);return(eval("element"+operator+"rule"))?true:false}}}}var validParts=[],rule=condition.replace(/^.*(==|\>=|\<=|\>|\<|!=|=~)/,""),subpath=condition.replace(/(==|\>=|\<=|\>|\<|!=|=~).*$/,"").replace(/\s$/,""),operator=condition.replace(rule,"").replace(subpath,"").replace(/\s/,""),element=subpath.split(".")[subpath.split(".").length-1];if(element===subpath){subpath=null}if(parts instanceof Array){if(!subpath){$.each(parts,function(){if(match(this[element],operator,rule)){validParts.push(this)}})}else{$.each(parts,function(){var currentChildren=children(this,"."+subpath),part=this;if(currentChildren instanceof Array){$.each(currentChildren,function(){if(match(this,operator,rule)){validParts.push(part);return false}})}else{if(match(currentChildren,operator,rule)){validParts.push(this)}}})}parts=validParts}else{if(!subpath){if(!match(parts[element],operator,rule)){parts=null}}else{var currentChildren=children(parts,"."+subpath);var currentChildren=children(parts,"."+subpath),valid=false;if(currentChildren instanceof Array){$.each(currentChildren,function(){if(match(this,operator,rule)){valid=true;return false}})}else{if(match(currentChildren,operator,rule)){valid=true}}parts=valid?parts:null}}}return(!parts)?[]:parts},remove:function(string){if(this.get(string)){eval("delete this.json."+string);if(string.match(/\[*.\]$/)){var _this=this;var filterNull=$.grep(eval("_this.json."+string.replace(/\[*.\]$/,"")),function(n,i){return(n)});eval("_this.json."+string.replace(/\[*.\]$/,"")+" = filterNull")}}},detectTypes:function(a){if(a.match(/^true$/i)){return true}else{if(a.match(/^false$/i)){return false}else{if(a.match(/^null|NaN|nil|undefined$/i)){return null}else{if(a.match(/^[0-9]*$/i)){return parseInt(a)}else{return a}}}}},throwError:function(a){if(typeof console!="undefined"){console.log(a)}}});
+var XMLtoJSON=Class.extend({init:function(a){this.xml=false,this.document=false;this.json={};this.duration=new Date();this.options=$.extend({url:false,xmlString:false,namespaces:false,valueIdentifier:"$",attributeIdentifier:"_",emptyValuesAsNull:false,modify:{},clearEmptyNodes:false,cache:false,detectTypes:false,filter:null,fallback:null,log:false},a);if(this.options.url){this.receiveXML()}if(this.options.xmlString){this.xml=this.options.xmlString}if(this.xml){this.parseXML();this.convertXML();if(this.options.fallback!=null&&(this.json=={}||this.json.parsererror)){this.options.fallback({message:"XML is invalid",code:500})}this.modifyJSON()}this.duration=new Date()-this.duration+" ms"},receiveXML:function(){var b=this.options.url,a;$.ajax({type:"GET",url:b,async:false,dataType:"text",cache:this.options.cache,complete:function(c){if(c.responseText){a=c.responseText.replace(/^\s+/,"")}}});if(a){this.xml=a}else{this.throwError("Cannot receive XML from "+this.options.url);if(this.options.fallback!=null){this.options.fallback({message:"Cannot receive XML from "+this.options.url,code:404})}}},parseXML:function(){this.xml=this.xml.replace(/^[\s\n\r\t]*[<][\?][xml][^<^>]*[\?][>]/,"");if(window.ActiveXObject){this.document=new ActiveXObject("Microsoft.XMLDOM");this.document.async=false;this.document.loadXML(this.xml)}else{this.document=new DOMParser();this.document=this.document.parseFromString(this.xml,"application/xml")}if(!this.xml||!this.document){this.throwError("Cannot parse XML")}},convertXML:function(){var b=this;(function a(d,h,n,j){var f=n.valueIdentifier,m=n.attributeIdentifier;if(d.nodeType===9){$.each(d.childNodes,function(){a(this,h,n,j)})}else{if(d.nodeType===1){var g=j[f]?{valueIdentifier:true}:{};var k=d.nodeName;var c=n.namespaces==true?true:false;var i={};if(k.indexOf(":")!=-1){g[k.substr(0,k.indexOf(":"))]=true}$.each(d.attributes,function(){var o=this.nodeName;var p=this.nodeValue;if(b.options.filter){p=b.options.filter(p)}if(b.options.detectTypes){p=b.detectTypes(p)}if(o==="xmlns"){j[f]=p;g[f]=true}else{if(o.indexOf("xmlns:")===0){j[o.substr(o.indexOf(":")+1)]=p}else{if(o.indexOf(":")!=-1){i[m+o]=p;g[o.substr(0,o.indexOf(":"))]=true}else{if(b.options.emptyValuesAsNull&&(p===""||p===null)){i[m+o]=null}else{i[m+o]=p}}}}});var e=c?j:g;$.each(e,function(o,p){if(e.hasOwnProperty(o)){i[m+"xmlns"]=i[m+"xmlns"]||{};i[m+"xmlns"][o]=p}});if(h[k] instanceof Array){h[k].push(i)}else{if(h[k] instanceof Object){h[k]=[h[k],i]}else{h[k]=i}}if(b.options.emptyValuesAsNull&&d.childNodes.length==0){h[k]=null}$.each(d.childNodes,function(){a(this,i,n,j)})}else{if(d.nodeType===3){var l=d.nodeValue;if(!l.match(/[\S]+/)){return}if(b.options.filter){l=b.options.filter(l)}if(b.options.detectTypes){l=b.detectTypes(l)}if(h[f] instanceof Array){h[f].push(l)}else{if(h[f] instanceof Object){h[f]=[h[f],l]}else{h[f]=l}}}}}})(this.document,this.json,this.options,{})},modifyJSON:function(){var _this=this,attributeIdentifier=this.options.attributeIdentifier;$.each(this.options.modify,function(url,modified){var all=url.match(/\.\*$/)?true:false;var url=all?url.replace(/\.\*$/,""):url;var content=_this.find(url);if(content){var newParent=modified.replace(/\.[^\.]*$/,"");if(modified.split(".").length>1){var newNode=newParent+'["'+modified.split(".")[modified.split(".").length-1]+'"]'}else{var newNode=modified}if(!all){_this.remove(url)}if(newParent.split(".").length>1){_this.createNodes(newParent)}_this.createNodes(modified);if(all){newNode=newNode.match(/\[\"\"\]/)?"":(newNode+".");$.each(content,function(key,value){if(key[0]!=attributeIdentifier){eval("_this.json."+newNode+key+" = value")}});$.each(_this.find(url),function(key,value){if(key[0]!=attributeIdentifier){_this.remove(url+"."+key)}})}else{eval("_this.json."+newNode+" = content")}if(_this.options.clearEmptyNodes){var parentNode=all?_this.find(url):_this.find(url.replace(/\.[^\.]*$/,""));var emptyNodes=true;$.each(parentNode,function(key,value){if(value instanceof Object){var children=0;for(var i in value){children++}if(children>1||children==1&&!_this.options.namespaces){return emptyNodes=false}}if(key[0]!=attributeIdentifier){return emptyNodes=false}});if(emptyNodes){all?_this.remove(url):_this.remove(url.replace(/\.[^\.]*$/,""))}}}})},createNodes:function(string){var _this=this;var node=this.get(string,false);if(node){return}(function checkNode(url,index){var current=url.split(".")[index];if(!current){return}var partUrl=[];for(var i=0;i<=index;i++){partUrl.push(url.split(".")[i])}partUrl=partUrl.join(".");var part=_this.get(partUrl,false);if(!part){eval("_this.json."+partUrl+"={}")}checkNode(url,index+1)})(string,0)},get:function(path,log){var array="",root=null,log=(log==false)?false:true;path=path.replace(/^\./,"");$.each(path.split("."),function(){if(this.match(/\[*.\]$/)){array+='["'+this.split("[")[0]+'"]'+this.match(/\[*.\]$/)[0]}else{array+='["'+this+'"]'}});try{root=eval("this.json"+array)}catch(e){if(log==true){this.throwError("Invalid path "+path)}}return(root)?root:(log==true?this.throwError("Could not access "+path):null)},find:function(path,condition){var _this=this,parts=[];function children(root,path){var url="",parts=[];$.each(path.split("."),function(i){var tempParts=[];if(i==0){url=this;tempParts=root}else{url+="."+this;if(this.match(/\[*.\]$/)){tempParts=parts[this.split("[")[0]][this.match(/\[*.\]$/)[0].replace(/[\[|\]]/g,"")]}else{if(parts instanceof Array){var part=this;$.each(parts,function(){if(this instanceof Array){$.each(this,function(){if(this[part]!=undefined){tempParts.push(this[part])}})}else{if(this[part]!=undefined){tempParts.push(this[part])}}})}else{tempParts=parts[this]}}}if(!tempParts||tempParts.length==0){_this.throwError("Invalid path "+url);parts=[];return false}else{parts=tempParts}});return parts}if(path.split(".")[0].match(/\[*.\]$/)){var index=path.split(".")[0].match(/\[*.\]$/)[0].replace(/[\[|\]]/g,"");var root=this.json[path.split(".")[0].replace(/\[.*\]/,"")][index]}else{var root=this.json[path.split(".")[0]]}parts=children(root,path);if(condition){function match(element,operator,rule){if(element&&operator&&rule){if(operator==="=~"){var options="";if(rule.match(/^\/.*/)&&rule.match(/\/.$/)){options=rule[rule.length-1];rule=rule.substring(0,rule.length-1)}rule=rule.replace(/^\//,"").replace(/\/$/,"");return(element.toString().match(new RegExp(rule,options)))?true:false}else{if(operator==="=="||operator==="!="){return(eval("element.toString()"+operator+"rule"))?true:false}else{rule=parseInt(rule);element=parseInt(element);return(eval("element"+operator+"rule"))?true:false}}}}var validParts=[],rule=condition.replace(/^.*(==|\>=|\<=|\>|\<|!=|=~)/,""),subpath=condition.replace(/(==|\>=|\<=|\>|\<|!=|=~).*$/,"").replace(/\s$/,""),operator=condition.replace(rule,"").replace(subpath,"").replace(/\s/,""),element=subpath.split(".")[subpath.split(".").length-1];if(element===subpath){subpath=null}if(parts instanceof Array){if(!subpath){$.each(parts,function(){if(match(this[element],operator,rule)){validParts.push(this)}})}else{$.each(parts,function(){var currentChildren=children(this,"."+subpath),part=this;if(currentChildren instanceof Array){$.each(currentChildren,function(){if(match(this,operator,rule)){validParts.push(part);return false}})}else{if(match(currentChildren,operator,rule)){validParts.push(this)}}})}parts=validParts}else{if(!subpath){if(!match(parts[element],operator,rule)){parts=null}}else{var currentChildren=children(parts,"."+subpath);var currentChildren=children(parts,"."+subpath),valid=false;if(currentChildren instanceof Array){$.each(currentChildren,function(){if(match(this,operator,rule)){valid=true;return false}})}else{if(match(currentChildren,operator,rule)){valid=true}}parts=valid?parts:null}}}return(!parts)?[]:parts},remove:function(string){if(this.get(string)){eval("delete this.json."+string);if(string.match(/\[*.\]$/)){var _this=this;var filterNull=$.grep(eval("_this.json."+string.replace(/\[*.\]$/,"")),function(n,i){return(n)});eval("_this.json."+string.replace(/\[*.\]$/,"")+" = filterNull")}}},detectTypes:function(a){if(a.match(/^true$/i)){return true}else{if(a.match(/^false$/i)){return false}else{if(a.match(/^null|NaN|nil|undefined$/i)){return null}else{if(a.match(/^[0-9]*$/i)){return parseInt(a)}else{return a}}}}},throwError:function(a){if(this.options.log){if(!window.console){window.console={log:function(b){alert(b)}}}console.log(a)}}});

0 comments on commit 455e88a

Please sign in to comment.
Something went wrong with that request. Please try again.