Prasanth Janardhanan

How to load from a JSON file to Javascript class object (Javascript/Typescript Serialization)

It is a common requirement to load a nested Javascript class from a JSON file. Sometimes you want to send the JSON across a network and load it back to a Javascript class.

For better clarity, let us understand the difference between a Javascript class instance and an Object. Take this class for example:

This is a class that draws a rectangle on the canvas

class Rectangle{
    public x:number=0
    public y:number=0
    public width:number=0
    public height:number=0
    
    public draw(ctx:CanvasRenderingContext2D)
    {
        ctx.strokeStyle = this.stroke
        ctx.rect(this.x,this.y, this.width, this.height)
        ctx.stroke();
    }
        
    public area()
    {
        return this.width * this.height           
    }
}

Suppose you have an instance of this rectangle and that you want to save the rectangle to a file. The easy solution would be to use JSON.stringify(rect). Once the object is converted into JSON string, it is easy to save to a file or send through wire to be saved to a database.

Continue Reading →