2013-02-27 32 views
1

我正在尋找在JavaScript中執行jQuery.parseJSON的方法,該方法解析一個json以返回一個JavaScript對象。我無法使用jQuery,因爲我構建的整個插件是獨立的JS,直到現在還沒有使用jQuery。有沒有這種東西已經在JavaScript中提供了?`jQuery.parseJSON`函數只有javascript(沒有jQuery)

+3

是的,JSON.parse – 2013-02-27 18:48:03

+0

@KevinB:編輯了問題。我打算提jQuery.parseJSON – user1240679 2013-02-27 18:51:08

+0

我的評論仍然適用。 – 2013-02-27 18:52:17

回答

1

使用本機JSON對象(這是唯一一次說「JSON對象」是正確的,它實際上是一個名爲JSON的對象)來操縱JSON字符串。

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON

使用JSON.parse(yourJSONString);序列化和JSON.stringify(yourJSONObject);反序列化。

如果您查看在線492上的jQuery core sourcejQuery.parseJSON只是JSON.parse的別名。

+0

'jbabey'編輯了這個問題。我打算提到jQuery.parseJSON – user1240679 2013-02-27 18:50:47

0

簡短的回答:

使用瀏覽器的本地方法JSON.parse()

window.JSON.parse(jsonString); 

龍答:

爲了得到它在舊的瀏覽器工作,你可以採用jQuery.parseJSONsource code,並刪除jQuery本身的任何依賴項。這裏是一個工作的獨立版本:

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

    if (data === null) { 
     return data; 
    } 

    var rvalidchars = /^[\],:{}\s]*$/; 
    var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g; 
    var rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g; 
    var rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g; 

    if (typeof data === "string") { 

     // Make sure leading/trailing whitespace is removed (IE can't handle it) 
     data = data.replace(/^\s+|\s+$/g, ''); 

     if (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))(); 
      } 
     } 
    } 

    // Error code here 
    //jQuery.error("Invalid JSON: " + data); 
}