Alternatives to eval()
I have been using eval which works in one webbrowser but not another (These are not your standard browsers but ones integrated with another application). In one my object of 300+ items is processed correctly. In the opther it processes items from 256 to the end but skips the first 255! the JSON is correct as well. Any alternatives to eval? perhaps a jsonToObject function. I am writing my own at the moment but I am hitting major time constraints and was hoping I didn't have to reinvent the wheel
Any ideas or functions?
Verymuch appreciated
So far I have this, I was going to try and base it on reverse polish. Not sure it's the most efficient, but for some reason it seemed like an interesting challenge. Part of me is folding to the pressures of the time I have though and so I need to be realistic and ask if therre are any methods already out there that can be shared with me.
var operatorStack = new Array();
var variableStack = new Array();
var valueStack = new Array();
var objectStack = new Array();
object.prototype.toJSON = function(){
}
function json(str){
this.value = str
}
/*
({"0":"Zero","1":{"A":"1","B":"2"},"2":{"C":"3","D":"4"},"3":{"E":"5","F":"^"}})
*/
json.prototype.toObject = function(){
var str = this.value;
var vbl = "";
var vlu = "";
for(var i = 0; i < str.length; i++){
var chr = str.charAt(i);
switch(chr){
case '{': //new Object();
objectStack.push = new Object();
operatorStack.push(chr);
break;
case '}': //close Object();
operatorStack.pop();
if(operat开发者_开发技巧orStack[operatorStack.length-1] == ':'){
objectStack[objectStack.length-2][vbl] = objectStack[objectStack.length-1];
}else{
return obj;
}
break;
case '"':
if(operatorStack[operatorStack.length-1] == '"'){
operatorStack.pop();
if(operatorStack[operatorStack.length-1] != ':'){
objectStack[objectStack.length-1][vbl] = val;
vbl = "";
val = "";
operatorStack.pop();
}else if(operatorStack[operatorStack.length-1] != ','){
operatorStack.pop();
}
}else{
operatorStack.push(chr);
}
break;
case ':':
operatorStack.push(chr);
break;
case ',':
operatorStack.push(chr);
break;
default:
if(operatorStack[operatorStack.length-1] == '"'){
switch(operatorStack[operatorStack.length-2]{
case '{': //we know it's a variable
vbl += chr;
break;
case ',': //we know it's a variable
vbl += chr;
break;
case ':': //we know it's a value
val += chr;
break;
}
}else{
alert("JSON not formed properly, alphanumerics not within quotes.")//JSON not formed properly
}
break;
}
}
return obj;
}
Thanks
https://github.com/douglascrockford/JSON-js
JSON.parse(text, reviver)
精彩评论