Commit 0912109f authored by jeresig's avatar jeresig

Expose the JSON parsing logic. Fixes #5914.

parent a6ef036b
...@@ -591,23 +591,7 @@ jQuery.extend({ ...@@ -591,23 +591,7 @@ jQuery.extend({
if ( typeof data === "string" ) { if ( typeof data === "string" ) {
// Get the JavaScript object, if JSON is used. // Get the JavaScript object, if JSON is used.
if ( type === "json" || !type && ct.indexOf("json") >= 0 ) { if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
// Make sure the incoming data is actual JSON data = jQuery.parseJSON( data );
// Logic borrowed from http://json.org/json2.js
if (/^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) {
// Try to use the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
data = window.JSON.parse( data );
} else {
data = (new Function("return " + data))();
}
} else {
jQuery.error( "Invalid JSON: " + data );
}
// If the type is "script", eval it in global context // If the type is "script", eval it in global context
} else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) { } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
......
...@@ -470,6 +470,28 @@ jQuery.extend({ ...@@ -470,6 +470,28 @@ jQuery.extend({
error: function( msg ) { error: function( msg ) {
throw msg; throw msg;
}, },
parseJSON: function( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if (/^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) {
// Try to use the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
data = window.JSON.parse( data );
} else {
data = (new Function("return " + data))();
}
} else {
jQuery.error( "Invalid JSON: " + data );
}
return data;
},
noop: function() {}, noop: function() {},
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment