TypeScript class to JSON

You can convert javascript objects into json strings using JSON.stringify() Since classes and instances of the classes are objects in javascript you can stringify them as well


use JSON.stringify() most thing in js are object.

class Hero{}
let Heros:Hero[] = JSON.stringify(response.data);

so the Heros is the Array you want :)


You can add a toJSON() function in your class. This function gets called automatically when JSON.stringify() is called on your class instance

class Person{
  constructor(readonly name){}

  toJSON(){
    return {
      firstName: this.name
    }
  }
}

Now if you console.log you class instance using JSON.stringify you will see this result

const person = new Person("Tom"); console.log(JSON.stringify(person));

Output

{
  firstName: "Tom"
}