如何在javascript中检测JSON支持?

Dan*_*Fox 9 javascript internet-explorer json

我试图检测JSON支持,if(JSON.parse) {}但它不起作用.有没有办法检测JSON支持?

xan*_*tos 22

取自json最着名的实现https://github.com/douglascrockford/JSON-js/blob/master/json2.js

var JSON;
if (JSON && typeof JSON.parse === 'function') {
    ....
}
Run Code Online (Sandbox Code Playgroud)

(我合并了两条if:if (!JSON) {第163行和if (typeof JSON.parse !== 'function') {第406行.

这里的技巧是var JSON,undefined如果没有,它将获得浏览器的JSON对象的值.

请注意,在最新版本的库中,他们将代码更改为:

if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
    ....
}
Run Code Online (Sandbox Code Playgroud)

(没有预先宣布var JSON)