Created
September 18, 2014 06:12
-
-
Save simplelife7/a883cce7249f80f41c88 to your computer and use it in GitHub Desktop.
【JS】字符串转换成JSON,兼容低级浏览器
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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