forked from vitotafuni/JSOTTEST
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JSON.js
81 lines (58 loc) · 1.8 KB
/
JSON.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
---
name: JSON
description: JSON encoder and decoder.
license: MIT-style license.
See Also: <http://www.json.org/>
requires: [Array, String, Number, Function]
provides: JSON
...
*/
if (typeof JSON == 'undefined') this.JSON = {};
//<1.2compat>
JSON = new Hash({
stringify: JSON.stringify,
parse: JSON.parse
});
//</1.2compat>
(function(){
var special = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'};
var escape = function(chr){
return special[chr] || '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4);
};
JSON.validate = function(string){
string = string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(string);
};
JSON.encode = JSON.stringify ? function(obj){
return JSON.stringify(obj);
} : function(obj){
if (obj && obj.toJSON) obj = obj.toJSON();
switch (typeOf(obj)){
case 'string':
return '"' + obj.replace(/[\x00-\x1f\\"]/g, escape) + '"';
case 'array':
return '[' + obj.map(JSON.encode).clean() + ']';
case 'object': case 'hash':
var string = [];
Object.each(obj, function(value, key){
var json = JSON.encode(value);
if (json) string.push(JSON.encode(key) + ':' + json);
});
return '{' + string + '}';
case 'number': case 'boolean': return '' + obj;
case 'null': return 'null';
}
return null;
};
JSON.decode = function(string, secure){
if (!string || typeOf(string) != 'string') return null;
if (secure || JSON.secure){
if (JSON.parse) return JSON.parse(string);
if (!JSON.validate(string)) throw new Error('JSON could not decode the input; security is enabled and the value is not secure.');
}
return eval('(' + string + ')');
};
})();