32 lines
842 B
JavaScript
32 lines
842 B
JavaScript
|
/**
|
||
|
* JSON parse.
|
||
|
*
|
||
|
* @see Based on jQuery#parseJSON (MIT) and JSON2
|
||
|
* @api private
|
||
|
*/
|
||
|
|
||
|
var rvalidchars = /^[\],:{}\s]*$/;
|
||
|
var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
|
||
|
var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
|
||
|
var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
|
||
|
var rtrimLeft = /^\s+/;
|
||
|
var rtrimRight = /\s+$/;
|
||
|
|
||
|
module.exports = function parsejson(data) {
|
||
|
if ('string' != typeof data || !data) {
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
|
||
|
|
||
|
// Attempt to parse using the native JSON parser first
|
||
|
if (global.JSON && JSON.parse) {
|
||
|
return JSON.parse(data);
|
||
|
}
|
||
|
|
||
|
if (rvalidchars.test(data.replace(rvalidescape, '@')
|
||
|
.replace(rvalidtokens, ']')
|
||
|
.replace(rvalidbraces, ''))) {
|
||
|
return (new Function('return ' + data))();
|
||
|
}
|
||
|
};
|