本文介绍了如何在javascript中检测JSON支持?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to detect JSON support with if(JSON.parse) {} but it doesn't works. Is there any way to detect the JSON support?

推荐答案

取自json最着名的实现

Taken from the json most famous implementation https://github.com/douglascrockford/JSON-js/blob/master/json2.js

var JSON;
if (JSON && typeof JSON.parse === 'function') {
    ....
}

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

(I have merged the two if: if (!JSON) { of line 163 and if (typeof JSON.parse !== 'function') { of line 406.

这里的诀窍是 var JSON 将获取浏览器的JSON对象的值, undefined 如果没有。

The trick here is that the var JSON will get the value of the JSON object of the browser, undefined if not.

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

Note that in the latest version of the library they changed the code to something like:

if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
    ....
}

(未预先声明 var JSON

这篇关于如何在javascript中检测JSON支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 10:20