-
Notifications
You must be signed in to change notification settings - Fork 1
/
json-ext.js
71 lines (63 loc) · 1.93 KB
/
json-ext.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
// Add ruby-like JSON ability to the standard JSON code.
(function () {
// A recursive function that traverses the raw object looking for special
// serialized objects to be de-serialized. Used by `JSON.load`
var json_object_load = function (obj) {
var key;
if (typeof obj.json_class === 'string') {
return (eval(obj.json_class)).jsonCreate(obj);
}
if (typeof obj === 'object') {
for (key in obj) {
obj[key] = json_object_load(obj[key]);
}
}
return obj;
};
// dump is just an alias of stringify since the needed `toJSON` hook is
// already in the stringify implementation.
JSON.dump = JSON.stringify;
// Works like JSON.parse, but then filters the output looking for object
// hooks. Allows custom objects to be de-serialized.
JSON.load = function (text) { return json_object_load(JSON.parse(text)); };
// Adds generic object hooks to about any object constructor.
JSON.extend = function (class) {
// Unserializes an object from JSON
class.jsonCreate = function(o) {
var obj, data, O, prototype;
O = function () {};
obj = new O();
prototype = class.prototype;
for (key in prototype) {
if (prototype.hasOwnProperty(key)) {
O.prototype[key] = prototype[key];
}
}
O.name = class.name;
obj.constructor = class;
data = o.data;
for (key in data) {
if (data.hasOwnProperty(key)) {
obj[key] = data[key];
}
}
return obj;
};
// Serialize any object to JSON
class.prototype.toJSON = function() {
var data = {};
if (this.constructor.name === 'Object') {
return this;
}
for (key in this) {
if (this.hasOwnProperty(key) && typeof this[key] !== 'function') {
data[key] = this[key];
}
}
return {
'json_class': this.constructor.name,
'data': data
};
};
};
}());