2013-02-27 26 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); 
}