SummerOfCode2006: json.js

File json.js, 3.6 KB (added by anonymous, 18 years ago)
Line 
1/*
2 json.js
3 2006-04-28
4
5 This file adds these methods to JavaScript:
6
7 object.toJSONString()
8
9 This method produces a JSON text from an object. The
10 object must not contain any cyclical references.
11
12 array.toJSONString()
13
14 This method produces a JSON text from an array. The
15 array must not contain any cyclical references.
16
17 string.parseJSON()
18
19 This method parses a JSON text to produce an object or
20 array. It will return false if there is an error.
21*/
22(function () {
23 var m = {
24 '\b': '\\b',
25 '\t': '\\t',
26 '\n': '\\n',
27 '\f': '\\f',
28 '\r': '\\r',
29 '"' : '\\"',
30 '\\': '\\\\'
31 },
32 s = {
33 array: function (x) {
34 var a = ['['], b, f, i, l = x.length, v;
35 for (i = 0; i < l; i += 1) {
36 v = x[i];
37 f = s[typeof v];
38 if (f) {
39 v = f(v);
40 if (typeof v == 'string') {
41 if (b) {
42 a[a.length] = ',';
43 }
44 a[a.length] = v;
45 b = true;
46 }
47 }
48 }
49 a[a.length] = ']';
50 return a.join('');
51 },
52 'boolean': function (x) {
53 return String(x);
54 },
55 'null': function (x) {
56 return "null";
57 },
58 number: function (x) {
59 return isFinite(x) ? String(x) : 'null';
60 },
61 object: function (x) {
62 if (x) {
63 if (x instanceof Array) {
64 return s.array(x);
65 }
66 var a = ['{'], b, f, i, v;
67 for (i in x) {
68 v = x[i];
69 f = s[typeof v];
70 if (f) {
71 v = f(v);
72 if (typeof v == 'string') {
73 if (b) {
74 a[a.length] = ',';
75 }
76 a.push(s.string(i), ':', v);
77 b = true;
78 }
79 }
80 }
81 a[a.length] = '}';
82 return a.join('');
83 }
84 return 'null';
85 },
86 string: function (x) {
87 if (/["\\\x00-\x1f]/.test(x)) {
88 x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
89 var c = m[b];
90 if (c) {
91 return c;
92 }
93 c = b.charCodeAt();
94 return '\\u00' +
95 Math.floor(c / 16).toString(16) +
96 (c % 16).toString(16);
97 });
98 }
99 return '"' + x + '"';
100 }
101 };
102
103 Object.prototype.toJSONString = function () {
104 return s.object(this);
105 };
106
107 Array.prototype.toJSONString = function () {
108 return s.array(this);
109 };
110})();
111
112String.prototype.parseJSON = function () {
113 try {
114 return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
115 this.replace(/"(\\.|[^"\\])*"/g, ''))) &&
116 eval('(' + this + ')');
117 } catch (e) {
118 return false;
119 }
120};
Back to Top