How to Convert an Object to a JSON String in Typescript ? - GeeksforGeeks (2024)

Last Updated : 16 Jul, 2024

Summarize

Comments

Improve

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
  • Using a Recursive Object Flattening Function

Using JSON.stringify()

  • 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 courseTypeScript 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.

JavaScript
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
}

Using json-stringify-safe library

Steps to use JSON-stringify-safe library with TypeScript:

Step 1: Initialize a New Project

Open your terminal or command prompt and navigate to the directory where you want to create your TypeScript project. Then run the following command.

npm init

Step 2: Install TypeScript as a dev dependency

You need to install TypeScript as a dev dependency in your project using the below command.

npm install typescript --save-dev

Step 3: Create a tsconfig.json file

The tsconfig.json file contains TypeScript compiler options for your project. Run the following command.

npx tsc --init

Step 4: Install json-stringify-safe

Install the JSON-stringify-safe library using the below command.

npm install json-stringify-safe

Step 5: Install node types

Install the @types/node into your project directory using the below command.

npm install --save @types/node

Step 6: Compile TypeScript Code

Use below command to compile TypeScript code.

npx tsc index.ts

Step 7: Run Your Code

Use the below command to run the code.

node index

Project Structure:

How to Convert an Object to a JSON String in Typescript ? - GeeksforGeeks (1)

project structure

Example: The below code uses JSON-stringify-safe library to convert an object into JSON string.

JavaScript
// index.tsconst stringifySafe =  require('json-stringify-safe');interface Course { courseName: string; courseFees: number;}const course: Course = { courseName: 'Javascript', courseFees: 30000}const jsonString: string =  stringifySafe(course);console.log(jsonString);

Output:

{
"courseName": "Javascript",
"courseFees": 30000
}

Using a Custom Serialization Function

In some cases, you may have complex objects with nested structures or non-serializable properties that need special handling when converting to JSON. In such scenarios, you can define a custom serialization function to handle the conversion process.

Example:

JavaScript
interface Course { courseName: string; courseFees: number; startDate: Date;}const course: Course = { courseName: "JavaScript", courseFees: 30000, startDate: new Date("2024-03-01"),};function customStringify(obj: any): string { return JSON.stringify(obj, (key, value) => { if (value instanceof Date) { // Serialize Date objects to ISO string return value.toISOString();  } return value; });}const jsonString = customStringify(course);console.log(jsonString);

Output:

{"courseName":"JavaScript","courseFees":30000,"startDate":"2024-03-01T00:00:00.000Z"}

Using TypeScript Decorators for Serialization

TypeScript decorators offer a declarative approach to modify the behavior of class declarations and members. For serialization, decorators can be utilized to annotate properties that require special handling or to automatically manage serialization without explicitly calling serialization logic in business code.

Step 1: Enable Decorators in TypeScript Configuration First, ensure your TypeScript project is set up to use decorators. Modify the tsconfig.json file to enable the experimentalDecorators option:

JavaScript
{ "compilerOptions": { "target": "ES5", "experimentalDecorators": true }}

Step 2: Define Serialization Decorators Create custom decorators to handle serialization logic for different types of properties. For example, you might have a decorator for formatting dates or excluding properties from the serialized output.

JavaScript
function SerializeDate(target: any, propertyKey: string) { let value: Date; const getter = function() { return value ? value.toISOString() : null; }; const setter = function(newVal: Date) { value = newVal; }; Object.defineProperty(target, propertyKey, { get: getter, set: setter, enumerable: true, configurable: true });}function ExcludeFromSerialization(target: any, propertyKey: string) { Object.defineProperty(target, propertyKey, { enumerable: false, configurable: true });}

Step 3: Define the Interface and Class Implement a class that uses these decorators, ensuring properties are handled according to the defined serialization rules.

JavaScript
interface Course { courseName: string; courseFees: number; startDate: Date;}class CourseImplementation implements Course { @ExcludeFromSerialization courseId: number; courseName: string; courseFees: number; @SerializeDate startDate: Date; constructor(courseId: number, name: string, fees: number, startDate: Date) { this.courseId = courseId; this.courseName = name; this.courseFees = fees; this.startDate = startDate; }}

Step 4: Create an Instance and Serialize Instantiate your class and serialize it using JSON.stringify, which will now respect the decorators’ behavior.

JavaScript
const course = new CourseImplementation(101, "JavaScript", 30000, new Date("2024-03-01"));const serializedCourse = JSON.stringify(course);console.log(serializedCourse);

Output:

{
"courseName": "JavaScript",
"courseFees": 30000,
"startDate": "2024-03-01T00:00:00.000Z"
}

Using a Recursive Object Flattening Function

In this approach, we define a recursive function to flatten complex objects into a simpler structure that can be easily serialized into JSON. This method is particularly useful for objects with nested structures, arrays, or non-serializable properties that require custom handling during serialization.

Example: The following example demonstrates how to use a recursive object flattening function to convert an object into a JSON string in TypeScript.

JavaScript
interface Course { courseName: string; courseFees: number; startDate: Date; additionalInfo?: { instructor: string; duration: string; };}const course: Course = { courseName: "JavaScript", courseFees: 30000, startDate: new Date("2024-03-01"), additionalInfo: { instructor: "John Doe", duration: "4 weeks" }};function flattenObject(obj: any, parent: string = '', res: any = {}): any { for (let key in obj) { const propName = parent ? `${parent}.${key}` : key; if (typeof obj[key] === 'object' && obj[key] !== null && !(obj[key] instanceof Date)) { flattenObject(obj[key], propName, res); } else { res[propName] = obj[key]; } } return res;}const flattenedCourse = flattenObject(course);const jsonString = JSON.stringify(flattenedCourse, (key, value) => { return value instanceof Date ? value.toISOString() : value;});console.log(jsonString);

Output:

{"courseName":"JavaScript","courseFees":30000,"startDate":"2024-03-01T00:00:00.000Z","additionalInfo.instructor":"John Doe","additionalInfo.duration":"4 weeks"}


P

pranay0911

How to Convert an Object to a JSON String in Typescript ? - GeeksforGeeks (2)

Improve

Next Article

How to Convert String to JSON in TypeScript ?

Please Login to comment...

How to Convert an Object to a JSON String in Typescript ? - GeeksforGeeks (2024)
Top Articles
sourcedefender
Does Proton VPN keep logs? | Proton
Compare Foods Wilson Nc
Craigslist Cars Augusta Ga
Loves Employee Pay Stub
Blanchard St Denis Funeral Home Obituaries
Senior Tax Analyst Vs Master Tax Advisor
A Complete Guide To Major Scales
Gw2 Legendary Amulet
Overzicht reviews voor 2Cheap.nl
Lost Pizza Nutrition
Natureza e Qualidade de Produtos - Gestão da Qualidade
Fire Rescue 1 Login
Richmond Va Craigslist Com
Diablo 3 Metascore
Top tips for getting around Buenos Aires
Operation Cleanup Schedule Fresno Ca
Copart Atlanta South Ga
bode - Bode frequency response of dynamic system
/Www.usps.com/International/Passports.htm
*Price Lowered! This weekend ONLY* 2006 VTX1300R, windshield & hard bags, low mi - motorcycles/scooters - by owner -...
All Breed Database
Yonkers Results For Tonight
Sorrento Gourmet Pizza Goshen Photos
Craigslist List Albuquerque: Your Ultimate Guide to Buying, Selling, and Finding Everything - First Republic Craigslist
Unable to receive sms verification codes
Paris Immobilier - craigslist
Accuradio Unblocked
Watertown Ford Quick Lane
Studentvue Calexico
Maisons près d'une ville - Štanga - Location de vacances à proximité d'une ville - Štanga | Résultats 201
Riverstock Apartments Photos
Kamzz Llc
Kaiserhrconnect
Ourhotwifes
Gideon Nicole Riddley Read Online Free
Appraisalport Com Dashboard /# Orders
SF bay area cars & trucks "chevrolet 50" - craigslist
Planet Fitness Santa Clarita Photos
Merkantilismus – Staatslexikon
Kornerstone Funeral Tulia
Sabrina Scharf Net Worth
If You're Getting Your Nails Done, You Absolutely Need to Tip—Here's How Much
Tableaux, mobilier et objets d'art
Dr Mayy Deadrick Paradise Valley
Hanco*ck County Ms Busted Newspaper
Here’s What Goes on at a Gentlemen’s Club – Crafternoon Cabaret Club
Slug Menace Rs3
What your eye doctor knows about your health
Ubg98.Github.io Unblocked
Aspen.sprout Forum
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated:

Views: 5975

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.