re-organize Gruntfile
[mootools.git] / Source / Utilities / JSON.js
blob011da3530f6d4c34fd6df5055292ca2ac2ca1f87
1 /*
2 ---
4 name: JSON
6 description: JSON encoder and decoder.
8 license: MIT-style license.
10 SeeAlso: <http://www.json.org/>
12 requires: [Array, String, Number, Function]
14 provides: JSON
16 ...
19 if (typeof JSON == 'undefined') this.JSON = {};
21 //<1.2compat>
23 JSON = new Hash({
24         stringify: JSON.stringify,
25         parse: JSON.parse
26 });
28 //</1.2compat>
30 (function(){
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);
48 } : function(obj){
49         if (obj && obj.toJSON) obj = obj.toJSON();
51         switch (typeOf(obj)){
52                 case 'string':
53                         return '"' + obj.replace(/[\x00-\x1f\\"]/g, escape) + '"';
54                 case 'array':
55                         return '[' + obj.map(JSON.encode).clean() + ']';
56                 case 'object': case 'hash':
57                         var string = [];
58                         Object.each(obj, function(value, key){
59                                 var json = JSON.encode(value);
60                                 if (json) string.push(JSON.encode(key) + ':' + json);
61                         });
62                         return '{' + string + '}';
63                 case 'number': case 'boolean': return '' + obj;
64                 case 'null': return 'null';
65         }
67         return null;
70 JSON.secure = true;
71 //<1.4compat>
72 JSON.secure = false;
73 //</1.4compat>
75 JSON.decode = function(string, secure){
76         if (!string || typeOf(string) != 'string') return null;
77     
78         if (secure == null) secure = JSON.secure; 
79         if (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.');
82         }
84         return eval('(' + string + ')');
87 })();