Created
May 11, 2012 05:18
-
-
Save RandomEtc/2657669 to your computer and use it in GitHub Desktop.
Extra escapey JSON encoding for node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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