9

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

7
  • 2
    Do you mean in a specific library or javascript itself? JSON is just a notation for javascript objects, javascript itself supports it natively. Commented 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. Commented Mar 14, 2012 at 9:38
  • 1
    Have u tried with if( 'JSON' in window )? Commented Mar 14, 2012 at 9:39
  • @websymphony no. I want to detect, if I can use JSON.parse function, or not. Commented 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) Commented Mar 14, 2012 at 9:39

2 Answers 2

22

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)

Sign up to request clarification or add additional context in comments.

2 Comments

HOw can you check if (JSON...) ?? youll get an error . its like doing if (lalala...) //error. The correct way is : if (typeof JSON==="undefined" ...)
@RoyiNamir You are right... I had forgotten a line of code... Before the if there should be a var JSON; . I have even added the "newer" version of the check.
0

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?

1 Comment

There are so many possible user agent that this is not practical. It is difficult to keep up to date. There is a long history of bugs with this kind of user-agent detection, and there are usually better solutions (feature-detection).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.