How to parse JSON string in TypeScript?

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.