diff --git a/lib/OpenLayers/Format/JSON.js b/lib/OpenLayers/Format/JSON.js index 4ba3138673..bd7c53f685 100644 --- a/lib/OpenLayers/Format/JSON.js +++ b/lib/OpenLayers/Format/JSON.js @@ -59,6 +59,14 @@ OpenLayers.Format.JSON = OpenLayers.Class(OpenLayers.Format, { */ pretty: false, + /** + * Property: nativeJSON + * {Boolean} Does the browser support native json? + */ + nativeJSON: (function() { + return !!(window.JSON && typeof JSON.parse == "function" && typeof JSON.stringify == "function"); + })(), + /** * Constructor: OpenLayers.Format.JSON * Create a new parser for JSON. @@ -87,15 +95,18 @@ OpenLayers.Format.JSON = OpenLayers.Class(OpenLayers.Format, { * {Object} An object, array, string, or number . */ read: function(json, filter) { - /** - * Parsing happens in three stages. In the first stage, we run the text - * against a regular expression which looks for non-JSON - * characters. We are especially concerned with '()' and 'new' - * because they can cause invocation, and '=' because it can cause - * mutation. But just to be safe, we will reject all unexpected - * characters. - */ - try { + var object; + if (this.nativeJSON) { + object = JSON.parse(json, filter); + } else try { + /** + * Parsing happens in three stages. In the first stage, we run the + * text against a regular expression which looks for non-JSON + * characters. We are especially concerned with '()' and 'new' + * because they can cause invocation, and '=' because it can + * cause mutation. But just to be safe, we will reject all + * unexpected characters. + */ if (/^[\],:{}\s]*$/.test(json.replace(/\\["\\\/bfnrtu]/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { @@ -107,7 +118,7 @@ OpenLayers.Format.JSON = OpenLayers.Class(OpenLayers.Format, { * begin a block or an object literal. We wrap the text in * parens to eliminate the ambiguity. */ - var object = eval('(' + json + ')'); + object = eval('(' + json + ')'); /** * In the optional third stage, we recursively walk the new @@ -127,17 +138,16 @@ OpenLayers.Format.JSON = OpenLayers.Class(OpenLayers.Format, { } object = walk('', object); } - - if(this.keepData) { - this.data = object; - } - - return object; } } catch(e) { // Fall through if the regexp test fails. } - return null; + + if(this.keepData) { + this.data = object; + } + + return object; }, /** @@ -159,7 +169,9 @@ OpenLayers.Format.JSON = OpenLayers.Class(OpenLayers.Format, { var type = typeof value; if(this.serialize[type]) { try { - json = this.serialize[type].apply(this, [value]); + json = (!this.pretty && this.nativeJSON) ? + JSON.stringify(value) : + this.serialize[type].apply(this, [value]); } catch(err) { OpenLayers.Console.error("Trouble serializing: " + err); }