Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you serialize javascript objects with methods using JSON?

I am looking for an enhancement to JSON that will also serialize methods. I have an object that acts as a collection of objects, and would like to serialize the methods of the collection object as well. So far I've located ClassyJSON. Any thoughts?

like image 645
David Robbins Avatar asked Apr 01 '26 01:04

David Robbins


2 Answers

Try to get away without serializing javascript code. That way lies a world of pain. Debugging will be much easier if code can only come from static files, not from a database. Instead, walk your JSON responses after you receive them and pass the appropriate data to the appropriate object constructors.

If you absolutely must serialize them, calling toString() on a function will return its source.

like image 89
moonshadow Avatar answered Apr 02 '26 13:04

moonshadow


I don't think serializing methods is ever a good idea. If you intend to run the code serverside, you open yourself to attacks. If you want to run it client side, you are better off just the local methods, possibly referencing the name of the method you are going to use in the serialized objects.

I do believe though that "f = "+function() {} will yield you a to string version that you can eval:

var test = "f = " + function() { alert("Hello"); };
eval(test)

And for good json handling, I would recommend prototype, which has great methods for serializing objects to json.

like image 44
Staale Avatar answered Apr 02 '26 15:04

Staale