JSON parsing for an object array

I have a problem with parsing JSON for an array of an object.

I have three JavaScript classes

  • Pet
  • Cat Extends Pet
  • Dog Extends Pet

I want to create an array of Pet objects, then I want to save it in the local browser storage as JSON.

Problem:

When I retrieve JSON and parse it into an array of an 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 a way to save the prototype elements as the original non-object?

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 in the local storage of the browser

var pets=[];
var cat = new Cat('imageUrl','name','soundUrl','favoriteFood');
pets.push(cat);
localStorage.setItem('pets', JSON.stringify(pets));

To get an array:

        if (localStorage.getItem('pets') !== null)
    {
     var pets = JSON.parse(localStorage.getItem('pets'));
    }
+4
source share
2 answers

, JSON ( ). , , - , , JSON ( ).

+4

@MauricePerry:

stringify Pet, , .

:

// add stringify function to your Pet class
function Pet(imageUrl, name, soundUrl) {
    ...
    this.stringify = function () {
        var jsonRepresentation = {};
        for (attr in this) {
            if (typeof this[attr] != "function") {
                jsonRepresentation[attr] = this[attr];
            }
        }
        return jsonRepresentation;
    };
};

// add a class property to your various pet subclasses
// e.g. Cat.prototype.class = "cat";

// create an instance of Cat
var cat = new Cat('imageUrl','name','soundUrl','favoriteFood');

// get the info to restore the cat instance later on
var animalInfo = cat.stringify();

/*
cat info would be like:
{
    "class": "cat",
    "imageUrl": "theUrl",
    "name": "theName",
    "soundUrl": "theSoundUrl",
    "favoriteFood": "theFavoriteFood"
}
 */

// then you would store the info to localStorage
...
// later you could retrieve you cat instance like so
var restoredAnimal;
switch(animalInfo.class) {
    case "cat":
        restoredAnimal = new Cat(animalInfo.imageUrl, animalInfo.name, animalInfo.soundUrl, animalInfo.favouriteFood)
        break;
    default:
        console.log('there is no such animal');
}
+3

Source: https://habr.com/ru/post/1541126/


All Articles