6 description: JSON encoder and decoder.
8 license: MIT-style license.
10 SeeAlso: <http://www.json.org/>
12 requires: [Array, String, Number, Function]
19 if (typeof JSON == 'undefined') this.JSON = {};
24 stringify: JSON.stringify,
32 var special = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'};
34 var escape = function(chr){
35 return special[chr] || '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4);
38 JSON.validate = function(string){
39 string = string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
40 replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
41 replace(/(?:^|:|,)(?:\s*\[)+/g, '');
43 return (/^[\],:{}\s]*$/).test(string);
46 JSON.encode = JSON.stringify ? function(obj){
47 return JSON.stringify(obj);
49 if (obj && obj.toJSON) obj = obj.toJSON();
53 return '"' + obj.replace(/[\x00-\x1f\\"]/g, escape) + '"';
55 return '[' + obj.map(JSON.encode).clean() + ']';
56 case 'object': case 'hash':
58 Object.each(obj, function(value, key){
59 var json = JSON.encode(value);
60 if (json) string.push(JSON.encode(key) + ':' + json);
62 return '{' + string + '}';
63 case 'number': case 'boolean': return '' + obj;
64 case 'null': return 'null';
75 JSON.decode = function(string, secure){
76 if (!string || typeOf(string) != 'string') return null;
78 if (secure == null) secure = JSON.secure;
80 if (JSON.parse) return JSON.parse(string);
81 if (!JSON.validate(string)) throw new Error('JSON could not decode the input; security is enabled and the value is not secure.');
84 return eval('(' + string + ')');