首先取自DouglasCrockford的方案,应该较多人使用。json.js和json2.js都差不多的。
// https://raw.github.com/douglascrockford/JSON-js/master/json.js
var 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 + '"';
}
// https://raw.github.com/douglascrockford/JSON-js/master/json_parse.js
var 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");
}
// https://raw.github.com/douglascrockford/JSON-js/master/json_parse_state.js
var 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用特殊字符转义
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") + '"';
}