14

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[]);
5
  • most things in js are objects so yes Commented Dec 13, 2016 at 7:04
  • @madalinivascu would you know any functions? Commented Dec 13, 2016 at 7:07
  • a useful question: stackoverflow.com/questions/13589880/… Commented Dec 13, 2016 at 7:11
  • That did it, would you like to post an answer so I can mark it? Commented Dec 13, 2016 at 7: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. Commented Dec 13, 2016 at 7:47

3 Answers 3

16

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

Sign up to request clarification or add additional context in comments.

Comments

10

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 Comment

best answer, I am working on TypedGraphQL ClassUserInput to userJson field in Prisma Model , this is to fix Index signature for type 'string' is missing in type ClassUserInput
0

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

3 Comments

thanks, but madalin gave me the answer first so if he make an answer I'll mark it. Still +1
This is not an answer. Besides it will not even compile.
stringify() returns a string, how can it be a Hero array?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.