Created
May 6, 2015 22:55
-
-
Save malectro/1b910ce89f0812bc1e3b to your computer and use it in GitHub Desktop.
Scratch pad for my safe-stringify method.
This file contains hidden or 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
var _ = require('underscore'); | |
var escape = require('escape-html'); | |
function ord(string) { | |
return string; | |
//return '' + string.charCodeAt(); | |
} | |
function pad(string, zeros) { | |
var count = zeros - string.length; | |
while (count) { | |
string = '0' + string; | |
count--; | |
} | |
return string; | |
} | |
var jsEscapes = { | |
'\\': '\\u005c', | |
'\'': '\\u0027', | |
'"': '\\u0022', | |
'>': '\\u003E', | |
'<': '\\u003C', | |
'&': '\\u0026', | |
'=': '\\u003D', | |
'-': '\\u002D', | |
';': '\\u003B', | |
'\u2028': '\\u2028', | |
'\u2029': '\\u2029', | |
}; | |
// Excape every ASCII character with a value less than 32. | |
_.times(32, function (z) { | |
jsEscapes[String.fromCharCode(z)] = '\\u' + pad(z.toString(16), 4); | |
}); | |
function recur(item) { | |
var ret; | |
if (_.isObject(item) || _.isArray(item)) { | |
if (item.toJSON) { | |
ret = item = item.toJSON(); | |
} else { | |
ret = new item.constructor(); | |
} | |
_.each(item, function (val, key) { | |
ret[key] = recur(val); | |
}); | |
} else if (_.isString(item)) { | |
ret = escape(item); | |
} else { | |
ret = item; | |
} | |
return ret; | |
} | |
module.exports = { | |
stringify: function (item) { | |
return JSON.stringify(item); | |
}, | |
safeStringify: function (item) { | |
var string = JSON.stringify(item); | |
var safe = ''; | |
var pos = 0; | |
for (var i = 0; i < string.length; i++) { | |
if (ch = jsEscapes[string[i]]) { | |
safe += string.slice(pos, i) + ch; | |
pos = i + 1; | |
} | |
} | |
safe += string.slice(pos); | |
console.log(safe); | |
return safe; | |
}, | |
parse: function () { | |
return JSON.parse.apply(JSON, arguments); | |
}, | |
}; | |
// python | |
/* | |
_js_escapes = { | |
ord('\\'): '\\u005C', | |
ord('\''): '\\u0027', | |
ord('"'): '\\u0022', | |
ord('>'): '\\u003E', | |
ord('<'): '\\u003C', | |
ord('&'): '\\u0026', | |
ord('='): '\\u003D', | |
ord('-'): '\\u002D', | |
ord(';'): '\\u003B', | |
ord('\u2028'): '\\u2028', | |
ord('\u2029'): '\\u2029' | |
} | |
# Escape every ASCII character with a value less than 32. | |
_js_escapes.update((ord('%c' % z), '\\u%04X' % z) for z in range(32)) | |
def escapejs(value): | |
"""Hex encodes characters for use in JavaScript strings.""" | |
return mark_safe(force_text(value).translate(_js_escapes)) | |
escapejs = allow_lazy(escapejs, six.text_type, SafeText) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment