Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript class to JSON

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[]);
like image 422
A. L Avatar asked Dec 13 '16 07:12

A. L


People also ask

How do I create a JSON in TypeScript?

obj = { "col1":{"Attribute1": "value1", "Attribute2": "value2", "Attribute3": "value3"}, "col2":{"Attribute1": "value4", "Attribute2": "value5", "Attribute3": "value6"}, "col3":{"Attribute1": "value7", "Attribute2": "value8", "Attribute3": "value9"} } this. output. stringify(this. obj);

Is there a JSON type in TypeScript?

The TypeScript comes up with the functionality of working with JSON Type data. JSON being the JavaScript Object Notation, is used to make a data model that is easy to write and read. We can easily analyze large and complex data set with this TypeScript JSON type.

What is toJSON () in JSON?

toJSON() calls the object's toISOString() method, which returns a string representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization, which can then be deserialized using the Date() constructor or Date. parse() as the reviver of JSON.

How do I Jsonify an object in TypeScript?

stringify() method to convert an object to JSON in TypeScript, e.g. const json = JSON. stringify(obj) . The JSON. stringify method takes a value, converts it to a JSON string and returns the result.


2 Answers

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"
}
like image 101
Abhijeet Sonawane Avatar answered Oct 25 '22 04:10

Abhijeet Sonawane


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

like image 40
madalinivascu Avatar answered Oct 25 '22 03:10

madalinivascu