From 0912109ffc86610161c769534df84400ccd1aa65 Mon Sep 17 00:00:00 2001 From: jeresig <jeresig@gmail.com> Date: Sat, 23 Jan 2010 16:51:51 -0500 Subject: Expose the JSON parsing logic. Fixes #5914. --- src/core.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'src/core.js') diff --git a/src/core.js b/src/core.js index 3ff95e020..5c9906888 100644 --- a/src/core.js +++ b/src/core.js @@ -470,6 +470,28 @@ jQuery.extend({ error: function( 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() {}, -- cgit v1.2.3