Permalink
Browse files

Escape unicode before submitting to the website.

Flask and Node.js disagree on how JSON should be encoded, unfortunatly.
  • Loading branch information...
1 parent 6ac185c commit e42c5bd43455ebfee18f19a548590d22bcc10b37 @mythmon mythmon committed Aug 27, 2012
Showing with 40 additions and 6 deletions.
  1. +24 −0 test.js
  2. +16 −6 utils.js
View
24 test.js
@@ -49,3 +49,27 @@ function eq(a, b, name) {
actual = utils.parseArgs(args);
eq(expected, actual, "Bare apostrophe");
})();
+
+
+(function test_escapeUnicode() {
+ var actual;
+ var expected;
+ var obj;
+
+ obj = {foo: 'bar'};
+ actual = utils.jsonStringifyUnicode(obj);
+ expected = JSON.stringify(obj);
+ eq(expected, actual, "Basic JSON");
+
+ actual = utils.jsonStringifyUnicode('I like π', true);
+ expected = '"I like π"';
+ eq(expected, actual, "Unicode mode");
+
+ actual = utils.jsonStringifyUnicode('I like π', false);
+ expected = '"I like \\u03c0"';
+ eq(expected, actual, "Escape mode");
+
+ actual = utils.jsonStringifyUnicode('I like π');
+ expected = '"I like \\u03c0"';
+ eq(expected, actual, "Default mode");
+})();
View
@@ -2,11 +2,11 @@ var _ = require('underscore');
var http = require('http');
var events = require('events');
-var request = function(path, method, data, emitter) {
+var request = function(path, method, data, emitter, unicode) {
if (data === undefined) {
data = {};
}
- var body = JSON.stringify(data);
+ var body = exports.jsonStringifyUnicode(data, unicode);
var options = {
host: config.standup.host,
port: config.standup.port,
@@ -48,7 +48,7 @@ var request = function(path, method, data, emitter) {
});
return emitter;
-}
+};
exports.request = request;
@@ -68,8 +68,8 @@ exports.ifAuthorized = function(user, channel, callback) {
};
exports.escapeRegExp = function(str) {
- return str.replace(/[-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
-}
+ return str.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
+};
/* Parse things like quotes strings from an argument list. */
exports.parseArgs = function(argList) {
@@ -104,4 +104,14 @@ exports.parseArgs = function(argList) {
}
});
return args;
-}
+};
+
+exports.jsonStringifyUnicode = function(str, emitUnicode) {
+ var json = JSON.stringify(str);
+ if (!emitUnicode) {
+ json = json.replace(/[\u007f-\uffff]/g, function(c) {
+ return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
+ });
+ }
+ return json;
+};

0 comments on commit e42c5bd

Please sign in to comment.