I tried to detect JSON support with if(JSON.parse) {} but it doesn't works. Is there any way to detect the JSON support?
-
2Do you mean in a specific library or javascript itself? JSON is just a notation for javascript objects, javascript itself supports it natively.websymphony– websymphony2012-03-14 09:37:47 +00:00Commented Mar 14, 2012 at 9:37
-
@websymphony, but it doesn't have the ability to parse natively, e.g, create an object given a string.Moo-Juice– Moo-Juice2012-03-14 09:38:56 +00:00Commented Mar 14, 2012 at 9:38
-
1Have u tried with if( 'JSON' in window )?stecb– stecb2012-03-14 09:39:00 +00:00Commented Mar 14, 2012 at 9:39
-
@websymphony no. I want to detect, if I can use JSON.parse function, or not.Danny Fox– Danny Fox2012-03-14 09:39:14 +00:00Commented Mar 14, 2012 at 9:39
-
I think he means if the JSON parser is present. Older versions of IE didn't have it (and there was at least a version of IE that had a buggy implementation)xanatos– xanatos2012-03-14 09:39:46 +00:00Commented Mar 14, 2012 at 9:39
2 Answers
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 Comments
if (JSON...) ?? youll get an error . its like doing if (lalala...) //error. The correct way is : if (typeof JSON==="undefined" ...)if there should be a var JSON; . I have even added the "newer" version of the check.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?