Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

improved get method

  • Loading branch information...
commit 1bc70dd5549bc59f66310cab01341ccdf1bd0eb5 1 parent 41aecbe
@derderderist authored
View
3  README.markdown
@@ -65,7 +65,8 @@ 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]) // Method to get a specific part of the JSON object. See examples/index.html to get further information.
+ data.get(<String> path) // Method to get a specific part of the JSON object
+ data.find(<String> path, [<String> conditions]) // Method to find a specific part of the JSON object without required knowledge of the JSON data structure. See examples/index.html to get further information.
## Browser compatibility
View
7 example/dependencies/application.js
@@ -1,11 +1,12 @@
$(document).ready(function(){
var result = new XMLtoJSON({
- url: 'xml/example.xml'
+ url: 'xml/example.xml',
+ log: true
});
$('#result, #time').hide();
$('#source textarea').val(result.xml);
$('#default textarea').val(js_beautify(JSON.stringify(result.json)));
- $('#examples div, #find div').each(function(){
+ $('#examples div, #get div, #find div').each(function(){
$(this).append('<span class="button">Run example</span>');
});
@@ -13,7 +14,7 @@ $(document).ready(function(){
var code = $(this).parent().find('pre').html();
code = code.replace(/(\n|\r|\v)/g,'').replace(/\s\s/g, '').replace('&gt;', '>').replace('&lt;', '<');
eval(code);
- if($(this).parent().parent().attr('id') == 'find'){
+ if($(this).parent().parent().attr('id') == 'get' || $(this).parent().parent().attr('id') == 'find'){
$(this).parent().append('<p class="result">' + JSON.stringify(data) +'</p>');
}
else{
View
86 example/index.html
@@ -59,6 +59,7 @@
</head>
<body>
+
<h1>List of examples for using XMLtoJSON</h1>
<div id="source">
<h2>XML source</h2>
@@ -152,7 +153,7 @@
</pre>
</div>
<div>
- <p>Remove 'response' node and move all children one level up</p>
+ <p>Clear 'response' node and move all children one level up</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml',
@@ -163,7 +164,7 @@
</pre>
</div>
<div>
- <p>Remove 'response.context' node and move all children into root</p>
+ <p>Clear 'response.context' node and move all children into root</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml',
@@ -174,7 +175,7 @@
</pre>
</div>
<div>
- <p>Remove 'response.context' node and move all children into root. Move 'response.version' as 'version' into root.</p>
+ <p>Clear 'response.context' node and move all children into root. Move 'response.version' as 'version' into root.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml',
@@ -186,13 +187,13 @@
</pre>
</div>
<div>
- <p>Remove 'response.context' node and move all children into root. Move 'response.version' as 'version' into root. Node 'response.context' and 'response' is now empty – clear node with param clearEmptyNodes.</p>
+ <p>Clear 'response.context' node and move all children into root. Move 'response.version' as 'release' into root. Node 'response.context' and 'response' is now empty – clear node with param clearEmptyNodes.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml',
modify: {
'response.context.*' : '.',
- 'response.version' : 'version'
+ 'response.version' : 'release'
},
clearEmptyNodes : true
});
@@ -273,15 +274,50 @@
</div>
<h2 id="time">Result</h2>
<textarea id="result" style="height: 300px;"></textarea>
- </div>
- <div id="find">
+ </div>
+
+ <div id="get">
+ <h2>Get JSON node with a string notation</h2>
+ <p>
+ The data.get() allows you to access a specified JSON node. A valid path is required, depending on the containing data structure (Arrays, Objects).
+ </p>
+ <div>
+ <p>Get node 'response.context.texts'.</p>
+ <pre>
+ var data = new XMLtoJSON({
+ url: 'xml/example.xml'
+ });
+ data = data.get('response.context.texts');
+ </pre>
+ </div>
+ <div>
+ <p>Get second text node in 'response.context.texts'.</p>
+ <pre>
+ var data = new XMLtoJSON({
+ url: 'xml/example.xml'
+ });
+ data = data.get('response.context.texts.text[0]');
+ </pre>
+ </div>
+ <div>
+ <p>Try to get invalid node 'response.foobar'.</p>
+ <pre>
+ var data = new XMLtoJSON({
+ url: 'xml/example.xml'
+ });
+ data = data.get('response.foobar');
+ </pre>
+ </div>
+ </div>
+
+ <div id="find">
<h2>Search and find in JSON</h2>
<p>
The data.find() method is a powerful way to access nodes (optionally with conditions). There is a logic implemented which allows a string notation without knowledge of the different node types –
- this means that you can access all Arrays inside of some other Arrays. It is not necessary to use a Array index. The following return statements are not parsed.
+ this means that you can access all Arrays inside of some other Arrays. It is not necessary to use a Array index.
</p>
<div>
- <p>Get all 'some' nodes in each 'response.context.misc.something.some'.</p>
+ <p>Find all 'some' nodes in each 'response.context.misc.something.some'.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml'
@@ -290,7 +326,7 @@ <h2 id="time">Result</h2>
</pre>
</div>
<div>
- <p>Get all 'something' nodes.</p>
+ <p>Find all 'something' nodes.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml'
@@ -299,7 +335,7 @@ <h2 id="time">Result</h2>
</pre>
</div>
<div>
- <p>Get all 'user' in 'response.context.users'.</p>
+ <p>Find all 'user' in 'response.context.users'.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml'
@@ -308,7 +344,7 @@ <h2 id="time">Result</h2>
</pre>
</div>
<div>
- <p>Get names of all 'user'.</p>
+ <p>Find names of all 'user'.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml'
@@ -317,7 +353,16 @@ <h2 id="time">Result</h2>
</pre>
</div>
<div>
- <p>Get all 'user' which are admins.</p>
+ <p>Find name of the second 'user'.</p>
+ <pre>
+ var data = new XMLtoJSON({
+ url: 'xml/example.xml'
+ });
+ data = data.find('response.context.users.user[1].name.$');
+ </pre>
+ </div>
+ <div>
+ <p>Find all 'user' which are admins.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml'
@@ -326,7 +371,7 @@ <h2 id="time">Result</h2>
</pre>
</div>
<div>
- <p>Get all 'texts' with a key attribute starting with 'general'.</p>
+ <p>Find all 'texts' with a key attribute starting with 'general'.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml'
@@ -335,7 +380,7 @@ <h2 id="time">Result</h2>
</pre>
</div>
<div>
- <p>Get all 'texts' with a value of 'My company'.</p>
+ <p>Find all 'texts' with a value of 'My company'.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml'
@@ -344,7 +389,7 @@ <h2 id="time">Result</h2>
</pre>
</div>
<div>
- <p>Get all 'user' with a age of >25 years.</p>
+ <p>Find all 'user' with a age of >25 years.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml'
@@ -353,7 +398,7 @@ <h2 id="time">Result</h2>
</pre>
</div>
<div>
- <p>Get all 'user' with are 30 years old.</p>
+ <p>Find all 'user' with are 30 years old.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml',
@@ -363,7 +408,7 @@ <h2 id="time">Result</h2>
</pre>
</div>
<div>
- <p>Get all 'something' with a 'some.other.url' with value www.google.com.</p>
+ <p>Find all 'something' with a 'some.other.url' with value www.google.com.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml',
@@ -373,7 +418,7 @@ <h2 id="time">Result</h2>
</pre>
</div>
<div>
- <p>Get all 'software' which are not named 'Adobe Photoshop'.</p>
+ <p>Find all 'software' which are not named 'Adobe Photoshop'.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml',
@@ -383,7 +428,7 @@ <h2 id="time">Result</h2>
</pre>
</div>
<div>
- <p>Get all 'users' if first 'user' has name 'Thomas'.</p>
+ <p>Find all 'users' if first 'user' has name 'Thomas'.</p>
<pre>
var data = new XMLtoJSON({
url: 'xml/example.xml',
@@ -393,6 +438,7 @@ <h2 id="time">Result</h2>
</pre>
</div>
</div>
+
</body>
</html>
View
38 lib/jquery.xmltojson.js
@@ -295,25 +295,27 @@ var XMLtoJSON = function(options){
// Get JSON by a full identifiable String splitted by '.'
this.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 + '"]';
+ var _this = this,
+ log = (log == false) ? false : true,
+ target = this.json,
+ path = path.replace(/^\./, ''),
+ currentPath = '',
+ tempPath = null;
+ (function select(index, log){
+ tempPath = path.split('.')[index];
+ if(tempPath){
+ currentPath += index === 0 ? tempPath : ('.' + tempPath);
+ target = tempPath.match(/\[*.\]$/) ? target[tempPath.split('[')[0]][tempPath.match(/\[([^\]]*)/)[1]] : target[tempPath];
+ if(!target){
+ if(log === true){
+ path === currentPath ? _this.throwError('Invalid path ' + path) : _this.throwError('Invalid part "' + currentPath + '" in path "' + path + '"');
+ }
+ return target;
+ }
+ select(index+1, log);
}
- });
- 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);
+ })(0, log);
+ return target;
}
// Find each JSON element by a given String splitted by '.' and additional conditions
View
2  lib/jquery.xmltojson.min.js
@@ -1 +1 @@
-var XMLtoJSON=function(options){this.init=function(){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},options);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"};this.receiveXML=function(){var url=this.options.url,response;$.ajax({type:"GET",url:url,async:false,dataType:"text",cache:this.options.cache,complete:function(data){if(data.responseText){response=data.responseText.replace(/^\s+/,"")}}});if(response){this.xml=response}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})}}};this.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")}};this.convertXML=function(){var _this=this;(function evaluate(node,obj,options,ns){var valueIdentifier=options.valueIdentifier,attributeIdentifier=options.attributeIdentifier;if(node.nodeType===9){$.each(node.childNodes,function(){evaluate(this,obj,options,ns)})}else{if(node.nodeType===1){var activeNamespace=ns[valueIdentifier]?{valueIdentifier:true}:{};var nodeName=node.nodeName;var addNamespaces=options.namespaces==true?true:false;var current={};if(nodeName.indexOf(":")!=-1){activeNamespace[nodeName.substr(0,nodeName.indexOf(":"))]=true}$.each(node.attributes,function(){var name=this.nodeName;var value=this.nodeValue;if(_this.options.filter){value=_this.options.filter(value)}if(_this.options.detectTypes){value=_this.detectTypes(value)}if(name==="xmlns"){ns[valueIdentifier]=value;activeNamespace[valueIdentifier]=true}else{if(name.indexOf("xmlns:")===0){ns[name.substr(name.indexOf(":")+1)]=value}else{if(name.indexOf(":")!=-1){current[attributeIdentifier+name]=value;activeNamespace[name.substr(0,name.indexOf(":"))]=true}else{if(_this.options.emptyValuesAsNull&&(value===""||value===null)){current[attributeIdentifier+name]=null}else{current[attributeIdentifier+name]=value}}}}});var namespace=addNamespaces?ns:activeNamespace;$.each(namespace,function(key,value){if(namespace.hasOwnProperty(key)){current[attributeIdentifier+"xmlns"]=current[attributeIdentifier+"xmlns"]||{};current[attributeIdentifier+"xmlns"][key]=value}});if(obj[nodeName] instanceof Array){obj[nodeName].push(current)}else{if(obj[nodeName] instanceof Object){obj[nodeName]=[obj[nodeName],current]}else{obj[nodeName]=current}}if(_this.options.emptyValuesAsNull&&node.childNodes.length==0){obj[nodeName]=null}$.each(node.childNodes,function(){evaluate(this,current,options,ns)})}else{if(node.nodeType===3){var value=node.nodeValue;if(!value.match(/[\S]+/)){return}if(_this.options.filter){value=_this.options.filter(value)}if(_this.options.detectTypes){value=_this.detectTypes(value)}if(obj[valueIdentifier] instanceof Array){obj[valueIdentifier].push(value)}else{if(obj[valueIdentifier] instanceof Object){obj[valueIdentifier]=[obj[valueIdentifier],value]}else{obj[valueIdentifier]=value}}}}}})(this.document,this.json,this.options,{})};this.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(/\.[^\.]*$/,""))}}}})};this.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)};this.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)};this.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};this.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")}}};this.detectTypes=function(string){if(string.match(/^true$/i)){return true}else{if(string.match(/^false$/i)){return false}else{if(string.match(/^null|NaN|nil|undefined$/i)){return null}else{if(string.match(/^[0-9]*$/i)){return parseInt(string)}else{return string}}}}};this.throwError=function(msg){if(this.options.log){if(!window.console){window.console={log:function(s){alert(s)}}}console.log(msg)}};this.init()};
+var XMLtoJSON=function(options){this.init=function(){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},options);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"};this.receiveXML=function(){var url=this.options.url,response;$.ajax({type:"GET",url:url,async:false,dataType:"text",cache:this.options.cache,complete:function(data){if(data.responseText){response=data.responseText.replace(/^\s+/,"")}}});if(response){this.xml=response}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})}}};this.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")}};this.convertXML=function(){var _this=this;(function evaluate(node,obj,options,ns){var valueIdentifier=options.valueIdentifier,attributeIdentifier=options.attributeIdentifier;if(node.nodeType===9){$.each(node.childNodes,function(){evaluate(this,obj,options,ns)})}else{if(node.nodeType===1){var activeNamespace=ns[valueIdentifier]?{valueIdentifier:true}:{};var nodeName=node.nodeName;var addNamespaces=options.namespaces==true?true:false;var current={};if(nodeName.indexOf(":")!=-1){activeNamespace[nodeName.substr(0,nodeName.indexOf(":"))]=true}$.each(node.attributes,function(){var name=this.nodeName;var value=this.nodeValue;if(_this.options.filter){value=_this.options.filter(value)}if(_this.options.detectTypes){value=_this.detectTypes(value)}if(name==="xmlns"){ns[valueIdentifier]=value;activeNamespace[valueIdentifier]=true}else{if(name.indexOf("xmlns:")===0){ns[name.substr(name.indexOf(":")+1)]=value}else{if(name.indexOf(":")!=-1){current[attributeIdentifier+name]=value;activeNamespace[name.substr(0,name.indexOf(":"))]=true}else{if(_this.options.emptyValuesAsNull&&(value===""||value===null)){current[attributeIdentifier+name]=null}else{current[attributeIdentifier+name]=value}}}}});var namespace=addNamespaces?ns:activeNamespace;$.each(namespace,function(key,value){if(namespace.hasOwnProperty(key)){current[attributeIdentifier+"xmlns"]=current[attributeIdentifier+"xmlns"]||{};current[attributeIdentifier+"xmlns"][key]=value}});if(obj[nodeName] instanceof Array){obj[nodeName].push(current)}else{if(obj[nodeName] instanceof Object){obj[nodeName]=[obj[nodeName],current]}else{obj[nodeName]=current}}if(_this.options.emptyValuesAsNull&&node.childNodes.length==0){obj[nodeName]=null}$.each(node.childNodes,function(){evaluate(this,current,options,ns)})}else{if(node.nodeType===3){var value=node.nodeValue;if(!value.match(/[\S]+/)){return}if(_this.options.filter){value=_this.options.filter(value)}if(_this.options.detectTypes){value=_this.detectTypes(value)}if(obj[valueIdentifier] instanceof Array){obj[valueIdentifier].push(value)}else{if(obj[valueIdentifier] instanceof Object){obj[valueIdentifier]=[obj[valueIdentifier],value]}else{obj[valueIdentifier]=value}}}}}})(this.document,this.json,this.options,{})};this.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(/\.[^\.]*$/,""))}}}})};this.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)};this.get=function(path,log){var _this=this,log=(log==false)?false:true,target=this.json,path=path.replace(/^\./,""),currentPath="",tempPath=null;(function select(index,log){tempPath=path.split(".")[index];if(tempPath){currentPath+=index===0?tempPath:("."+tempPath);target=tempPath.match(/\[*.\]$/)?target[tempPath.split("[")[0]][tempPath.match(/\[([^\]]*)/)[1]]:target[tempPath];if(!target){if(log===true){path===currentPath?_this.throwError("Invalid path "+path):_this.throwError('Invalid part "'+currentPath+'" in path "'+path+'"')}return target}select(index+1,log)}})(0,log);return target};this.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};this.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")}}};this.detectTypes=function(string){if(string.match(/^true$/i)){return true}else{if(string.match(/^false$/i)){return false}else{if(string.match(/^null|NaN|nil|undefined$/i)){return null}else{if(string.match(/^[0-9]*$/i)){return parseInt(string)}else{return string}}}}};this.throwError=function(msg){if(this.options.log){if(!window.console){window.console={log:function(s){alert(s)}}}console.log(msg)}};this.init()};
Please sign in to comment.
Something went wrong with that request. Please try again.