Hi Friends 👋,

Welcome to Infinitbility ❤️!

Today, we are going to see how we can convert the object to JSON string in typescript, here we will use the built-in method JSON.stringify() to convert data object to JSON string.

When you want to pass data to API or anywhere then you should stringify your JSON.

Here, we will create a sample object and then we use JSON.stringify() to convert the object to a string.

So let’s start the code…

interface User {
  id: number;
  name: string;
  domain?: string;
  age?: number;
  isActive?: boolean;
}

let user: User = {
  id: 1,
  name: "infinitbility",
  domain: "infinitbility.github.io",
  age: 2,
  isActive: 1
};

console.log(user);
console.log(typeof user);
let jsonString : string = JSON.stringify(user);
console.log(jsonString);
console.log(typeof jsonString);

When you run the above code you will get object data and object data type before stringify.

After stringify, it will show object data as a string and data type also string.

check out the output of the above example.

convert object to json string example
TypeScript, convert object to json string example

All the best 👍.