Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Escape unicode before submitting to the website.

Flask and Node.js disagree on how JSON should be encoded, unfortunatly.
  • Loading branch information...
commit e42c5bd43455ebfee18f19a548590d22bcc10b37 1 parent 6ac185c
@mythmon mythmon authored
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
22 utils.js
@@ -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;
+};
Please sign in to comment.
Something went wrong with that request. Please try again.