Navigate back to the homepage

How to convert string to json in typescript?

Infinitbility
TypeScript
April 14th, 2022 · 1 min read
keep affilitate

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.

1interface User {
2 id: number;
3 name: string;
4 domain?: string;
5 age?: number;
6 isActive?: boolean;
7}
8
9let user: User = {
10 id: 1,
11 name: "infinitbility",
12 domain: "infinitbility.com",
13 age: 2,
14 isActive: 1
15};
16
17let jsonString : string = JSON.stringify(user);
18console.log(jsonString);
19console.log(typeof jsonString);
20let userJson: object = JSON.parse(jsonString);
21console.log(userJson);
22console.log(userJson.name);
23console.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 👍.

Follow me on Twitter

Join our email list and get notified about new content

No worries, I respect your privacy and I will never abuse your email.

Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.

melio affilitate

Looking For React Native Tutorial?

we are trying to create the best Tutorial for react native developers.

When you want a daily updates about React Native Tutorial or infinitbility update subscribe to our newsletter.

Read React Native Tutorial

Request New Tutorial or Article on mail [email protected]

Guide book

Guidebook: The Javascript Monorepo Photoshop Guide

Tutorials

Categories

More articles from Infinitbility

How to convert string to boolean in typescript?

TypeScript, convert string to boolean example.

April 13th, 2022 · 1 min read

How to convert a string to camel case in typescript?

TypeScript, convert string case to camel case example.

April 11th, 2022 · 1 min read
© 2020–2022 Infinitbility
About
Link to $https://medium.com/infinitbilityLink to $https://www.facebook.com/InfinitbilityLink to $https://github.com/infinitbilityLink to $https://twitter.com/infinitbilityLink to $https://www.buymeacoffee.com/infinitbilityLink to $mailto:[email protected]