Permalink
Browse files

native JSON detection. closes #227

  • Loading branch information...
1 parent fdb020d commit 0fd6d5f9a56af815b79f0cbd2370ae4fbfed4ba7 @paulirish paulirish committed Dec 4, 2011
Showing with 7 additions and 0 deletions.
  1. +7 −0 feature-detects/json.js
View
@@ -0,0 +1,7 @@
+// native JSON support.
+// developer.mozilla.org/en/JSON
+
+// this will also succeed if you've loaded the JSON2.js polyfill ahead of time
+// ... but that should be obvious. :)
+
+Modernizr.addTest('json', !!window.JSON && !!JSON.parse);

7 comments on commit 0fd6d5f

This can guarantee a JSON object being available but cannot say if its native or not. It will fail if someone is using a 3rd party JSON library, right?
I was wondering if checking JSON.toLocaleString() for [object JSON] value is a nice way to check or not?

thats what mentioned in 0fd6d5f#L0R4 ?

Owner

stucox replied Jul 17, 2013

Is that a problem @chinchang? Many feature detects will return true once an accurate polyfill has been loaded – which would often be desirable behaviour: you wouldn't want to polyfill the JSON object again, and once polyfilled you can make use of it as if native.

Interested to know your use case for knowing if it's native or a library/polyfill.

@stucox I have experienced this a lot of times where I wanted to run some code on an external website and required JSON to do so. Now my code loads its own JSON lib which fallbacks to available JSON, if any. Issue here is that my code shouldn't be dependent on the website's JSON override. I strictly need to detect if the JSON on that website is native or not and use it only if its native. Hope I am clear here :)

For such purpose I have for now found the best solution to be as follows:

JSON && JSON.stringify && JSON.stringify.toString().indexOf('[native code]')

Ofcourse it will fail if someone intentionally has the word [native code] in his stringify polyfill, but I am taking it as 'should not happen'.

Owner

stucox replied Jul 18, 2013

If the website has already loaded a JSON lib, why can't your code use that? Why can it only use it if it's native?

Owner

stucox replied Jul 18, 2013

Ok fair enough. Do you happen to know which JSON libs break, and in what ways? If they're simply incomplete then maybe you could detect the specific functions you need, but if they're just plain broken then yeah I can imagine that's annoying!

I can see you have a good use case, but I think it's probably fairly rare and most users would be happy returning true if a polyfilled JSON object was present anyway. Plus it could open a can of worms if we expected every detect in Modernizr to tell the difference between native and polyfill implementations...

Please sign in to comment.