Skip to content Skip to sidebar Skip to footer

Dojo: How To Load An Object (containing Other Objects) From Json?

I have an object model that I want to be able to save. I am going to export it to JSON and then read it back in as JSON. Saving to JSON is easy. Just use this: JSON.stringify(t

Solution 1:

I think you would be better off returning a JSON object that contains just the data you need to serialize, not the whole class. Then your loadFromJson method would be a little easier to implement, and you wont be sending unnecessary data over the network. Example toJson():

toJson: function() {
    return JSON.stringify({
        photos: this.photos,
        someImportantProp: this.someImportantProp,
        anotherProp: this.anotherProp
    });
}

Solution 2:

JSON is not the same thing as a JavaScript object, in fact, it's only a subset. JSON only allows arrays, objects and of course basic types like Strings, booleans, numbers and null. You can find the entire specification here.

If you really want to keep the functions you can use the eval() function, but this is not really recommended, because it indeed parses those functions. If the evaluated content contains malicious input, then that is being executed as well.

For example:

eval("myObj = { getSum: function getSum(a, b) { return a + b; } }");
myObj.getSum(1, 2); // Returns 3

You can better attempt to save the state of the object (name and url for example) and rebuild it once you parse it again, that is what happens in other programming languages as well. For example, if you're serializing/deserializing an object in Java.

Post a Comment for "Dojo: How To Load An Object (containing Other Objects) From Json?"