Skip to content

Instantly share code, notes, and snippets.

@Paxa
Created July 23, 2010 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Paxa/487295 to your computer and use it in GitHub Desktop.
Save Paxa/487295 to your computer and use it in GitHub Desktop.
/*
Script: mJSON.js
JSON encoder and decoder.
License:
MIT-style license.
See Also:
<http://www.json.org/>
*/
var mJSON = new Hash({
$specialChars: {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'},
$replaceChars: function(chr){
return mJSON.$specialChars[chr] || '\\u00' + Math.floor(chr.charCodeAt() / 16).toString(16) + (chr.charCodeAt() % 16).toString(16);
},
encode: function(obj){
switch ($type(obj)){
case 'string':
return '"' + obj.replace(/[\x00-\x1f\\"]/g, mJSON.$replaceChars) + '"';
case 'array':
return '[' + String(obj.map(mJSON.encode).filter($defined)) + ']';
case 'object': case 'hash':
var string = [];
Hash.each(obj, function(value, key){
var json = mJSON.encode(value);
if (json) string.push(mJSON.encode(key) + ':' + json);
});
return '{' + string + '}';
case 'number': case 'boolean': return String(obj);
case false: return 'null';
}
return null;
},
decode: function(string, secure){
if ($type(string) != 'string' || !string.length) return null;
if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null;
return eval('(' + string + ')');
}
});
Native.implement([Hash, Array, String, Number], {
tomJSON: function(){
return mJSON.encode(this);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment