Skip to content

Instantly share code, notes, and snippets.

@simplelife7
Created September 18, 2014 06:12
Show Gist options
  • Save simplelife7/a883cce7249f80f41c88 to your computer and use it in GitHub Desktop.
Save simplelife7/a883cce7249f80f41c88 to your computer and use it in GitHub Desktop.
【JS】字符串转换成JSON,兼容低级浏览器
function parseJSON( data ) {
var // JSON RegExp
rvalidchars = /^[\],:{}\s]*$/
, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g
, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g
, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g
;
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
data = data.replace(/^\s+|\s+$/g, '');
if ( data && rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
return '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment