Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I have seen references to some browsers natively supporting JSON parsing/serialization of objects safely and efficiently via the
window.JSON
Object, but details are hard to come by. Can anyone point in the right direction? What are the methods this Object exposes? What browsers is it supported under?
–
All modern browsers support native JSON encoding/decoding (Internet Explorer 8+, Firefox 3.1+, Safari 4+, and Chrome 3+). Basically,
JSON.parse(str)
will parse the JSON string in
str
and return an object, and
JSON.stringify(obj)
will return the JSON representation of the object
obj
.
More details on the
MDN article
.
–
–
–
–
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
jQuery.error( "Invalid JSON: " + data );
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
The advantage of using json2.js is that it will only install a parser if the browser does not already have one. You can maintain compatibility with older browsers, but use the native JSON parser (which is more secure and faster) if it is available.
Browsers with Native JSON:
Firefox 3.1+
Safari 4.0.3+
Opera 10.5+
Internally it checks if browser supports .JSON.parse, and (if available) calls native window.JSON.parse.
If not, does parse itself.
Thanks for contributing an answer to Stack Overflow!
-
Please be sure to
answer the question
. Provide details and share your research!
But
avoid
…
-
Asking for help, clarification, or responding to other answers.
-
Making statements based on opinion; back them up with references or personal experience.
To learn more, see our
tips on writing great answers
.