Categories
TypeScript Answers

How to parse JSON string in TypeScript?

Spread the love

Sometimes, we want to parse JSON string in TypeScript.

In this article, we’ll look at how to parse JSON string in TypeScript.

How to parse JSON string in TypeScript?

To parse JSON string in TypeScript, we can call JSON.parse and assign a type to the variable that’s assigned to the parsed JSON object.

For instance, we write

interface MyObj {
  myString: string;
  myNumber: number;
}

const obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');

to call JSON.parse with '{ "myString": "string", "myNumber": 4 }' to return the object that’s parsed from the JSON string.

We then assign the returned object to the obj variable which has type MyObj.

In the MyObj interface, we list the properties that we expect to be in the parsed object along with their types.

Conclusion

To parse JSON string in TypeScript, we can call JSON.parse and assign a type to the variable that’s assigned to the parsed JSON object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *