Debian Codegraph @

jsonpickleJS/unpickler.js

raw
1 /**
2 * jsonPickle/javascript/unpickler -- Conversion from music21p jsonpickle streams
3 *
4 * Copyright (c) 2013-14, Michael Scott Cuthbert and cuthbertLab
5 * Based on music21 (=music21p), Copyright (c) 2006–14, Michael Scott Cuthbert and cuthbertLab
6 *
7 * usage:
8 *
9 * js_obj = unpickler.decode(json_string);
10 *
11 *
12 */
13
14 define(['./util', './handlers', './tags'], function(util, handlers, tags) {
15 var unpickler = {};
16
17 unpickler.decode = function (string, user_handlers, options) {
18 var params = {
19 keys: false,
20 safe: false,
21 reset: true,
22 backend: JSON,
23 };
24
25 util.merge(params, options);
26
27 var use_handlers = {};
28 util.merge(use_handlers, handlers); // don't screw up default handlers...
29 util.merge(use_handlers, user_handlers);
30
31 // backend does not do anything -- it is there for
32 // compat with py-JSON-Pickle
33 if (params.context === undefined) {
34 var unpickler_options = {
35 keys: params.keys,
36 backend: params.backend,
37 safe: params.safe,
38 };
39 context = new unpickler.Unpickler(unpickler_options, use_handlers);
40 }
41 var jsonObj = params.backend.parse(string);
42 return context.restore(jsonObj, params.reset);
43 };
44
45 unpickler.Unpickler = function (options, handlers) {
46 var params = {
47 keys: false,
48 safe: false,
49 };
50 util.merge(params, options);
51 this.keys = params.keys;
52 this.safe = params.safe;
53
54 this.handlers = handlers;
55 //obsolete...
56 //this._namedict = {};
57
58 // The namestack grows whenever we recurse into a child object
59 this._namestack = [];
60
61 // Maps objects to their index in the _objs list
62 this._obj_to_idx = {};
63 this._objs = [];
64 };
65
66 unpickler.Unpickler.prototype.reset = function () {
67 //this._namedict = {};
68 this._namestack = [];
69 this._obj_to_idx = {};
70 this._objs = [];
71 };
72
73 /**
74 * Restores a flattened object to a JavaScript representation
75 * as close to the original python object as possible.
76 *
77 * Requires that javascript
78 */
79 unpickler.Unpickler.prototype.restore = function (obj, reset) {
80 if (reset) {
81 this.reset();
82 }
83 return this._restore(obj);
84 };
85
86 unpickler.Unpickler.prototype._restore = function (obj) {
87 var has_tag = unpickler.has_tag;
88 var restore = undefined;
89
90 if (has_tag(obj, tags.ID)) {
91 restore = this._restore_id.bind(this);
92 } else if (has_tag(obj, tags.REF)) {
93 // backwards compat. not supported
94 } else if (has_tag(obj, tags.TYPE)) {
95 restore = this._restore_type.bind(this);
96 } else if (has_tag(obj, tags.REPR)) {
97 // backwards compat. not supported
98 } else if (has_tag(obj, tags.OBJECT)) {
99 restore = this._restore_object.bind(this);
100 } else if (has_tag(obj, tags.TUPLE)) {
101 restore = this._restore_tuple.bind(this);
102 } else if (has_tag(obj, tags.SET)) {
103 restore = this._restore_set.bind(this);
104 } else if (util.is_list(obj)) {
105 restore = this._restore_list.bind(this);
106 } else if (util.is_dictionary(obj)) {
107 restore = this._restore_dict.bind(this);
108 } else {
109 restore = function (obj) { return obj; };
110 }
111 return restore(obj);
112 };
113
114 unpickler.Unpickler.prototype._restore_id = function (obj) {
115 return this._objs[obj[tags.ID]];
116 };
117
118 unpickler.Unpickler.prototype._restore_type = function (obj) {
119 var typeref = unpickler.loadclass(obj[tags.TYPE]);
120 if (typeref === undefined) {
121 return obj;
122 } else {
123 return typeref;
124 }
125 };
126
127 unpickler.Unpickler.prototype._restore_object = function (obj) {
128 var class_name = obj[tags.OBJECT];
129 var handler = this.handlers[class_name];
130 if (handler !== undefined && handler.restore !== undefined) {
131 var instance = handler.restore(obj);
132 instance[tags.PY_CLASS] = class_name;
133 return this._mkref(instance);
134 } else {
135 var cls = unpickler.loadclass(class_name);
136 if (cls === undefined) {
137 obj[tags.PY_CLASS] = class_name;
138 return this._mkref(obj);
139 }
140 var instance = this._restore_object_instance(obj, cls);
141 instance[tags.PY_CLASS] = class_name;
142 if (handler !== undefined && handler.post_restore !== undefined) {
143 return handler.post_restore(instance);
144 } else {
145 return instance;
146 }
147 }
148 };
149 unpickler.Unpickler.prototype._loadfactory = function (obj) {
150 var default_factory = obj['default_factory'];
151 if (default_factory === undefined) {
152 return undefined;
153 } else {
154 obj['default_factory'] = undefined;
155 return this._restore(default_factory);
156 }
157 };
158
159
160 unpickler.Unpickler.prototype._restore_object_instance = function (obj, cls) {
161 //var factory = this._loadfactory(obj);
162 var args = unpickler.getargs(obj);
163 if (args.length > 0) {
164 args = this._restore(args);
165 }
166 // not using factory... does not seem to apply to JS
167 var instance = unpickler.construct(cls, args);
168 this._mkref(instance);
169 return this._restore_object_instance_variables(obj, instance);
170 };
171
172 unpickler.Unpickler.prototype._restore_object_instance_variables = function (obj, instance) {
173 var has_tag = unpickler.has_tag;
174 var restore_key = this._restore_key_fn();
175 var keys = [];
176 for (var k in obj) {
177 if (obj.hasOwnProperty(k)) {
178 keys.push(k);
179 }
180 }
181 keys.sort();
182 for (var i = 0; i < keys.length; i++) {
183 var k = keys[i];
184 if (tags.RESERVED.indexOf(k) != -1) {
185 continue;
186 }
187 var v = obj[k];
188 this._namestack.push(k);
189 k = restore_key(k);
190 var value = undefined;
191 if (v !== undefined && v !== null) {
192 value = this._restore(v);
193 }
194 // no setattr checks...
195 instance[k] = value;
196 this._namestack.pop();
197 }
198 if (has_tag(obj, tags.SEQ)) {
199 if (instance.push !== undefined) {
200 for (var v in obj[tags.SEQ]) {
201 instance.push(this._restore(v));
202 }
203 } // no .add ...
204 }
205
206 if (has_tag(obj, tags.STATE)) {
207 instance = this._restore_state(obj, instance);
208 }
209 return instance;
210 };
211
212
213 unpickler.Unpickler.prototype._restore_state = function (obj, instance) {
214 // only if the JS object implements __setstate__
215 if (instance.__setstate__ !== undefined) {
216 var state = this._restore(obj[tags.STATE]);
217 instance.__setstate__(state);
218 } else {
219 instance = this._restore(obj[tags.STATE]);
220 }
221 return instance;
222 };
223
224 unpickler.Unpickler.prototype._restore_list = function (obj) {
225 var parent = [];
226 this._mkref(parent);
227 var children = [];
228 for (var i = 0; i < obj.length; i++) {
229 var v = obj[i];
230 var rest = this._restore(v);
231 children.push(rest);
232 }
233 parent.push.apply(parent, children);
234 return parent;
235 };
236 unpickler.Unpickler.prototype._restore_tuple = function (obj) {
237 // JS having no difference between list, tuple, set -- returns Array
238 var children = [];
239 var tupleContents = obj[tags.TUPLE];
240 for (var i = 0; i < tupleContents.length; i++) {
241 children.push(this._restore(tupleContents[i]));
242 }
243 return children;
244 };
245 unpickler.Unpickler.prototype._restore_set = function (obj) {
246 // JS having no difference between list, tuple, set -- returns Array
247 var children = [];
248 var setContents = obj[tags.SET];
249 for (var i = 0; i < setContents.length; i++) {
250 children.push(this._restore(setContents[i]));
251 }
252 return children;
253 };
254 unpickler.Unpickler.prototype._restore_dict = function (obj) {
255 var data = {};
256 //var restore_key = this._restore_key_fn();
257 var keys = [];
258 for (var k in obj) {
259 if (obj.hasOwnProperty(k)) {
260 keys.push(k);
261 }
262 }
263 keys.sort();
264 for (var i = 0; i < keys.length; i++) {
265 var k = keys[i];
266 var v = obj[k];
267
268 this._namestack.push(k);
269 data[k] = this._restore(v);
270 // no setattr checks...
271 this._namestack.pop();
272 }
273 return data;
274 };
275
276 unpickler.Unpickler.prototype._restore_key_fn = function () {
277 if (this.keys) {
278 return function (key) {
279 if (key.indexOf(tags.JSON_KEY) == 0) {
280 key = unpickler.decode(key.slice(tags.JSON_KEY.length),
281 this.handlers,
282 {context: this, keys: this.keys, reset: false}
283 );
284 return key;
285 }
286 };
287 } else {
288 return function (key) { return key; };
289 }
290 };
291
292 // _refname not needed...
293
294 unpickler.Unpickler.prototype._mkref = function (obj) {
295 // does not use id(obj) in javascript
296 this._objs.push(obj);
297 return obj;
298 };
299
300
301 unpickler.getargs = function (obj) {
302 var seq_list = obj[tags.SEQ];
303 var obj_dict = obj[tags.OBJECT];
304 if (seq_list === undefined || obj_dict === undefined) {
305 return [];
306 }
307 var typeref = unpickler.loadclass(obj_dict);
308 if (typeref === undefined) {
309 return [];
310 }
311 if (typeref['_fields'] !== undefined) {
312 if (typeref['_fields'].length == seq_list.length) {
313 return seq_list;
314 }
315 }
316 return [];
317 };
318
319 unpickler.loadclass = function (module_and_name) {
320 var main_check = '__main__.';
321 if (module_and_name.indexOf(main_check) == 0) {
322 module_and_name = module_and_name.slice(main_check.length);
323 }
324 var parent = window;
325 var module_class_split = module_and_name.split('.');
326 for (var i = 0; i < module_class_split.length; i++) {
327 var this_module_or_class = module_class_split[i];
328 parent = parent[this_module_or_class];
329 if (parent === undefined) {
330 return parent;
331 }
332 }
333 return parent;
334 };
335
336 unpickler.has_tag = function (obj, tag) {
337 if ((typeof obj == 'object') &&
338 (obj[tag] !== undefined)) {
339 return true;
340 } else {
341 return false;
342 }
343 };
344
345 // http://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible
346 unpickler.construct = function (constructor, args) {
347 function F() {
348 return constructor.apply(this, args);
349 }
350 F.prototype = constructor.prototype;
351 return new F();
352 };
353
354 if (jsonpickle !== undefined) {
355 jsonpickle.unpickler = unpickler;
356 }
357 return unpickler;
358 });