Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JSON to re-build the Javascript Object?

I have an object like this:

var someObj = Class.create ({
  initialize: function(objName){
      this.objName = objName;
  }
});

I can use

o = new someObj("objName");

to make an obj. I can use Object.toJSON(o) to change the o to become a JSON String, but I want the JSON String convert back to someObj, so, I use eval() to pass the JSON String to become an object, but the question is, it can become a JS Obj, but the constructor of "o" is not someObj. How can I eval the JSON String by using "someObj" as the constructor?

like image 647
DNB5brims Avatar asked Oct 19 '09 15:10

DNB5brims


2 Answers

JSON strings cannot represent objects with member functions, so the only thing you will get out of a JSON string is raw data. Assuming the toJSON method results in a JSON string representing an object with all the non-function members of your class instance, you should be able to take the resulting object and attach the prototype to get all the functions back. For example, using jQuery's handy extend function:

var o = new someObj("objName");
var json = Object.toJSON(o);
var json_obj = eval(json);
$.extend(json_obj, someObj.prototype);
json_obj.someMethodDefinedOnsomeObj()

Depending on how the framework you are using to represent classes in JavaScript makes use of the prototypal object model, your milage may very with the above example. Also, using eval() creates a security hole, so if you do not trust where the JSON string is coming from, you should use a different de-serialization method. Just for full coverage, here is how I did it with raw prototypes:

function Animal(name){
    this.name = name;
}
Animal.prototype.talk = function(){
    console.log("My name is "+this.name);
}

var a = new Animal("Brendan Eich");
a.talk();

var json = '{name: "Tim Berners-Lee"}'
var b = eval(b);
$.extend(b, Animal.prototype);
b.talk();

In a firebug console this produces the output:

My name is Brendan Eich

My name is Tim Berners-Lee

like image 151
pcardune Avatar answered Oct 21 '22 02:10

pcardune


See JSON revivers at http://json.org/js.html

 var myObject = JSON.parse(myJSONtext, reviver);

The optional reviver parameter is a function that will be called for every key and value at every level of the final result. Each value will be replaced by the result of the reviver function. This can be used to reform generic objects into instances of pseudoclasses, or to transform date strings into Date objects.

like image 2
Mike Samuel Avatar answered Oct 21 '22 01:10

Mike Samuel