Hi Friends 👋,

Welcome to Infinitbility ❤️!

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

When you get a string from any API or anywhere and it looks like JSON key-value pair for example

'{"id":1,"name":"infinitbility","domain":"infinitbility.com","age":2,"isActive":1}'

and you won’t use it then first you to parse it.

let’s start code.

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

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

let jsonString : string = JSON.stringify(user);
console.log(jsonString);
console.log(typeof jsonString);
let userJson: object = JSON.parse(jsonString);
console.log(userJson);
console.log(userJson.name);
console.log(typeof userJson);

When you run the above code first console show string data, the second data type then we are parsing…

Now console shows object data and their data type.

check the following output.

Output

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

All the best 👍.