總結js實現字符串轉JSON對象的幾種方法


  在瀏覽器前端實現字符串轉JSON對象,有多種方法,總結如下:

  • 方法1.  js函數,eval()

語法:

var obj = eval ("(" + txt + ")");  //必須把文本包圍在括號中,這樣才能避免語法錯誤

eval()定義:eval() 函數可計算某個字符串,並執行其中的的 JavaScript 代碼。

由於 JSON 語法是 JavaScript 語法的子集,JavaScript 函數 eval() 可用於將 JSON 文本轉換為 JavaScript 對象。

注意:當字符串中包含表達式時,eval() 函數也會編譯並執行,轉換會存在安全問題。

參考:JSON 使用 | 菜鳥教程JavaScript eval() 函數

 

  • 方法2.  瀏覽器自帶對象JSON,JSON.parse()

語法:

JSON.parse(text[, reviver])
//text:必需, 一個有效的 JSON 字符串。解析前要確保你的數據是標准的 JSON 格式,否則會解析出錯。
//reviver: 可選,一個轉換結果的函數, 將為對象的每個成員調用此函數。

JSON.parse()比eval()安全,而且速度更快支持主流瀏覽器:Firefox 3.5,IE 8,Chrome,Opera 10,Safari 4。

注意:IE8兼容模式,IE 7,IE 6,會存在兼容性問題。

解決方法:引入json2.jsJSON官網

<!--[if lte IE 7]>
<script src="json2.js"></script>    
<![endif]-->

json2.js關鍵源碼分析:

//paring過程分為4個步驟。
//第一個步驟是將unicode字符替換為轉義字符。
//js在處理多種字符時是有問題的,不是悄悄的刪掉他們,就是把他們當作行結束符。
            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            
//第二個步驟如下:
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
 
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
 
            if (/^[\],:{}\s]*$/
                    .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
 
//第三步驟:調用eval命令
//'{'在js中有語法歧義傾向:可以是程序塊或者對象字面值。所以這里使用括號來避免歧義                
                j = eval('(' + text + ')');
json2.js關鍵源碼

參考:JSON.parse() | 菜鳥教程json2.js 簡析(個人學習) - 奮斗小小鳥的專欄

 

  • 方法3.  引用jQuery插件,$.parseJSON()

語法:

$.parseJSON(json)  //json:String類型,傳入格式有誤的JSON字符串可能導致拋出異常

$.parseJSON()關鍵源碼分析:

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
      return window.JSON.parse( data );
 }

// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
     .replace( rvalidtokens, "]" )
     .replace( rvalidbraces, "")) ) {
        return ( new Function( "return " + data ) )();
}
$.parseJSON()關鍵源碼

參考:jQuery.parseJSON()方法 | 菜鳥教程jQuery靜態方法parseJSON方法使用和源碼分析 - -洋仔

 

  • 方法4.  AJAX請求獲取JSON數據時,$.getJSON() 

語法:

jQuery.getJSON(url,data,success(data,status,xhr))
//url    必需。規定將請求發送的哪個 URL。
//data    可選。規定連同請求發送到服務器的數據。
//success(data,status,xhr)    可選。規定當請求成功時運行的函數。

這個時候返回的data已經是JSON對象,不需要再進行轉換。

$.getJSON() 是簡寫的 Ajax 函數,等價於:

$.ajax({
  url: url,
  data: data,
  success: callback,
  dataType: "json"
});

參考:jQuery ajax - getJSON() 方法

 

 


 

 總結:

1.建議使用JSON.parse()方法;如果需兼容IE6/7,再引入json2.js文件(下載)。 相對應的JSON.stringify()方法,可用來將JSON對象轉換為字符串

2.如果頁面里已經引用jQuery,你又不想再引入多余文件(json2.js),也可以使用$.parseJSON()方法。

3.使用eval()時,必須保證字符串里沒有可執行代碼。

4.如果是通過AJAX獲取JSON數據,直接用$.getJSON()函數,或者在$.ajax()中加入參數dataType: "json",就可以直接得到JSON對象。

 

 

參考:JS字符串轉換為JSON的四種方法筆記 - 天使不哭 - 博客園


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM