How to use JSON.stringify() In JSON
- Define an interface Course that describes the shape of the object with the required properties and their types.
- Declare the course variable with the Course type. This ensures the object matches the interface shape.
- Assign the object literal to the course – TypeScript will check it matches the interface.
- Call JSON.stringify() on the typed object.
Example: The below code will explain the use of the JSON.stringify() method to convert an object to JSON string.
interface Course {
courseName: string;
courseFees: number;
}
const course: Course = {
courseName: "Javascript",
courseFees: 30000,
};
const jsonString = JSON.stringify(course);
console.log(jsonString);
Output:
{
"courseName": "Javascript",
"courseFees": 30000
}
How to Convert an Object to a JSON String in Typescript ?
In TypeScript, an object is a collection of related data and functionality. Objects are made up of properties and methods. Properties describe the object, methods describe what it can do.
Table of Content
- Using JSON.stringify()
- Using json-stringify-safe library
- Using a Custom Serialization Function
- Using TypeScript Decorators for Serialization