I have a problem with parsing JSON to array of object.
I have three JavaScript classes
I want to create array of Pet objects, then I want to store it in the browser local storage as JSON.
The problem:
When I retrieve the JSON and parse it to array of object, the prototype of the element changed from Cat or Dog, to Object, so when I test
pets[0] instanceof Cat // always false
pets[0] instanceof Dog // always false
Is there I way to keep the prototype of elements as the original not object ?
The classes:
function Pet(imageUrl, name, soundUrl) {
this.imageUrl = imageUrl;
this.name = name;
this.soundUrl = soundUrl;
this.talk = function() {
};
}
function Cat(imageUrl, name, soundUrl, favoriteFood) {
Pet.apply(this,arguments);
this.favoriteFood=favoriteFood;
}
Cat.prototype=new Pet();
Cat.prototype.constructor = Cat;
function Dog(imageUrl, name, soundUrl, walkingTime) {
Pet.apply(this,arguments);
this.walkingTime=walkingTime;
}
Dog.prototype=new Pet();
Dog.prototype.constructor = Dog;
After creating the array I have to save it to the browser local storage
var pets=[];
var cat = new Cat('imageUrl','name','soundUrl','favoriteFood');
pets.push(cat);
localStorage.setItem('pets', JSON.stringify(pets));
To retrieve the array:
if (localStorage.getItem('pets') !== null)
{
var pets = JSON.parse(localStorage.getItem('pets'));
}
Yes, in JSON you only have plain vanilla objects (and arrays). The only way I can see to deal with this problem is to add an extra property giving the class, then after the parsing of you JSON, you would need to convert the resulting objects into animals (to give them life in a way).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With