Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing JSON to array of object [duplicate]

I have a problem with parsing JSON to array of object.

I have three JavaScript classes

  1. Pet
  2. Cat extend Pet
  3. Dog extend Pet

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'));
    }
like image 603
Mohd Alomar Avatar asked Mar 20 '23 14:03

Mohd Alomar


1 Answers

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).

like image 121
Maurice Perry Avatar answered Mar 22 '23 23:03

Maurice Perry