2011-05-19 110 views
1

我一直在使用eval,它可以在一個瀏覽器中使用,但不是另一種(這些不是您的標準瀏覽器,而是與其他應用程序集成的瀏覽器)。在我的一個300+項目的對象被正確處理。在opther中,它處理從256到最後的項目,但跳過前255個項目! JSON也是正確的。任何替代eval?也許是一個jsonToObject函數。我正在寫我自己的時刻,但我受到了時間的限制,並希望我不必重新發明輪子eval()的替代品

任何想法或功能?

Verymuch讚賞

到目前爲止,我有這個,我要去嘗試,並基於它逆波蘭。不確定它是最有效的,但由於某種原因,它似乎是一個有趣的挑戰。我的一部分工作正在折磨着我所經歷的壓力,所以我需要現實一些,並詢問是否有任何方法可以與我分享。

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(operatorStack[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; 
} 

感謝

+0

你爲什麼不使用JSON解析器? – 2011-05-19 15:07:52

回答