Created
July 23, 2010 11:08
-
-
Save Paxa/487295 to your computer and use it in GitHub Desktop.
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
/* | |
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