12

I have a class array where the class looks like:

class Tag{
    select: string;
    search: string;
}

I want to convert it to JSON where it'll probably look like [{select: "blah", search: "bleh"}, {...}, {...}].

Is this possible? Because from the Angular 2 tutorial you can do the opposite with the line:

.map((r: Response) => r.json().data as Hero[]);
A. L
  • 11,695
  • 23
  • 85
  • 163
  • most things in js are objects so yes – madalinivascu Dec 13 '16 at 07:04
  • @madalinivascu would you know any functions? – A. L Dec 13 '16 at 07:07
  • a useful question: http://stackoverflow.com/questions/13589880/using-json-stringify-on-custom-class – madalinivascu Dec 13 '16 at 07:11
  • That did it, would you like to post an answer so I can mark it? – A. L Dec 13 '16 at 07:22
  • Do you mean you want to convert an **instance** of this class into a plain old JS object? Or you want to convert an **instance** of this class into a JSON string? Or you want to convert the class itself--what would that mean? Also, note that this question has nothing to do with angular, and very little to do with TypeScript. –  Dec 13 '16 at 07:47

3 Answers3

15

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

madalinivascu
  • 32,064
  • 4
  • 39
  • 55
6

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"
}
1

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

Cery
  • 203
  • 5
  • 14