I tried to detect JSON support with if(JSON.parse) {}
but it doesn't works. Is there any way to detect the JSON support?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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') {
....
}
(I have merged the two if
: if (!JSON) {
of line 163 and if (typeof JSON.parse !== 'function') {
of line 406.
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') {
....
}
(without pre-declaring the var JSON
)
回答2:
Might not exactly count as an answer to what was asked, but would perhaps parsing the user agent (navigator) and checking for versions you are confident support the parser be a possible alternative?