分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
一、JSON.js
首先取自DouglasCrockford的方案,应该较多人使用。json.js和json2.js都差不多的。
// https://raw.github.com/douglascrockford/JSON-js/master/json.jsvar meta = { // table of character substitutions '\b' : '\\b', '\t' : '\\t', '\n' : '\\n', '\f' : '\\f', '\r' : '\\r', '"' : '\\"', '\\' : '\\\\'};function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function(a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)) .slice(-4); }) + '"' : '"' + string + '"';}
二、依然取自D.C大大,在json_parse.js里。
// https://raw.github.com/douglascrockford/JSON-js/master/json_parse.jsvar escapee = { '"' : '"', '\\' : '\\', '/' : '/', b : '\b', f : '\f', n : '\n', r : '\r', t : '\t'};string = function() { // Parse a string value. var hex, i, string = ', uffff; // When parsing for string values, we must look for " and \ characters. if (ch === '"') { while (next()) { if (ch === '"') { next(); return string; } else if (ch === '\\') { next(); if (ch === 'u') { uffff = 0; for (i = 0; i < 4; i += 1) { hex = parseInt(next(), 16); if (!isFinite(hex)) { break; } uffff = uffff * 16 + hex; } string += String.fromCharCode(uffff); } else if (typeof escapee[ch] === 'string') { string += escapee[ch]; } else { break; } } else { string += ch; } } } error("Bad string");}
三、仍为D.C大大的,在json_parse_state.js里。
// https://raw.github.com/douglascrockford/JSON-js/master/json_parse_state.jsvar escapes = { // Escapement translation table '\\' : '\\', '"' : '"', '/' : '/', 't' : '\t', 'n' : '\n', 'r' : '\r', 'f' : '\f', 'b' : '\b'};function debackslashify(text) { // Remove and replace any backslash escapement. return text.replace(/\\(?:u(.{4})|([^u]))/g, function(a, b, c) { return b ? String.fromCharCode(parseInt(b, 16)) : escapes[c]; });}
四、旧版的json.js,moontools也是这种方案的?。这里/[\x00-\x1f\\"]/g代表什么意思呢?
// JSON用特殊字符转义var special = { '\b' : '\\b', '\t' : '\\t', '\n' : '\\n', '\f' : '\\f', '\r' : '\\r', '"' : '\\"', '\\' : '\\\\'};var escape = function(chr) { return special[chr] || '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4)};function _escape(obj){ return '"' + obj.replace(/[\x00-\x1f\\"]/g, escape) + '"'}
五、我当前的方案,感觉比较简单明了,但会不会有未知的问题呢?待继续明了。
function StringAs(string) { return '"' + string.replace(/(\\|\"|\n|\r|\t)/g, "\\$1") + '"';}