First, Json.js
First from the Douglascrockford scheme, should be more people use. Json.js and Json2.js are the same.
Https://raw.github.com/douglascrockford/JSON-js/master/json.js
var meta = {//table of character substitutions< c2/> ' \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
//Backsla SH characters, then we can safely slap some quotes 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)
. Slice ( -4);
}) + ' "': '" ' + string + ' "';
}
two, still taken from D.C big, in Json_parse.js.
Https://raw.github.com/douglascrockford/JSON-js/master/json_parse.js
var escapee = {' '
: ' ',
' \ \ \ ': ' \ \ ',
'/': '/',
B: ' \b ',
f: ' \f ',
N: ' \ n ',
r: ' \ r ', T:
' \ \ \ \ n '}; string = function () {
//Parse a string value.
var hex, I, String = ', uffff;
When parsing to 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 ());
if (!isfinite (hex)) {break
;
}
UFFFF = uffff * + hex;
}
string + + String.fromCharCode (UFFFF);
} else if (typeof escapee[ch] = = = ' String ') {
string + = Escapee[ch];
} else {break
;
}
} else {
string + = ch;
}}
Error ("Bad string");
}
three, still for D.C big, in Json_parse_state.js.
Https://raw.github.com/douglascrockford/JSON-js/master/json_parse_state.js
var escapes = {//escapement Translation table ' \ \ ': ' \ n ', ' ': ' '
, '/': '/', '
t ': ' \
\ ', '/' ': ' \ 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)): Escapes[c];}
Four, the old version of the Json.js,moontools is also this scheme. Here/[\x00-\x1f\\ "What does]/g mean?"
JSON uses special characters escape
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). Slice ( -4)
};
function _escape (obj) {return
' "' + obj.replace (/[\x00-\x1f\\"]/g, Escape) + ' "
}
Five, my current plan, the feeling is relatively simple and clear, but will not have the unknown question. Remain clear.
function Stringas (string) {return
' "' + string.replace (/(\\|\" |\n|\r|\t)/g, "\\$1") + ' "';
}
finally found there are http://relucent.iteye.com/blog/646016 here