Javascript 将字符串转换为JSON

阅读(2637)

默认使用 JSON.parse 完成转换,对不支持此方法的浏览器做了兼容。

/**
 * 字符串转换为JSON对象
 * 来自 jQuery 1.6.2
 */
function parseJSON (data) {
    if ( typeof data !== "string" || !data ) {
        return null;
    }

    var rvalidchars = /^[\],:{}\s]*$/,
        rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
        rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
        rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
        rbrace = /^(?:\{.*\}|\[.*\])$/;

    // 如果包含空格,IE可能出错
    data = data.replace(/^\s+|\s+$/g, '');

    if(rbrace.test( data )) {
        data = (data+'').replace(/^\s+|\s+$/g, '');

        if ( window.JSON && window.JSON.parse ) {
            return window.JSON.parse( data );
        }

        // Make sure the incoming data is actual JSON
        // Logic borrowed from http://json.org/json2.js
        if ( rvalidchars.test( data.replace( rvalidescape, "@" ) 
            .replace( rvalidtokens, "]" )
            .replace( rvalidbraces, "")) ) {

            return (new Function( "return " + data ))();
        }
    } else {
        return data;
    }
}

Tags: json