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[]);
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);
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.
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.
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.
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"
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With