Use native JSON if available. p=fredj,me r=bartvde,tschaub,elemoine (closes #1807)

git-svn-id: http://svn.openlayers.org/trunk/openlayers@10952 dc9f47b5-9b13-0410-9fdd-eb0c1a62fdaf
This commit is contained in:
ahocevar
2010-12-07 16:56:49 +00:00
parent 831420aac2
commit 92493cc12b

View File

@@ -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);
}