Skip to content

Instantly share code, notes, and snippets.

@RandomEtc
Created May 11, 2012 05:18
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save RandomEtc/2657669 to your computer and use it in GitHub Desktop.
Save RandomEtc/2657669 to your computer and use it in GitHub Desktop.
Extra escapey JSON encoding for node.js
// preserve Twitter's style of JSON string encoding...
// escape higher value unicode (lowercase hex)
// escape < and > (uppercase hex)
// escape / in strings (\/)
// hugs! https://gist.github.com/1306986
// http://stackoverflow.com/questions/4901133/json-and-escaping-characters
function escapedStringify(s, emit_unicode) {
var json = JSON.stringify(s);
return emit_unicode ? json : json.replace(/\//g,
function(c) {
return '\\/';
}
).replace(/[\u003c\u003e]/g,
function(c) {
return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4).toUpperCase();
}
).replace(/[\u007f-\uffff]/g,
function(c) {
return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
}
);
}
module.exports = {
stringify: escapedStringify
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment