Parse JSON String in TypeScript
In this tutorial, we will take a JSON string, and parse it to an object in TypeScript.
To parse a JSON string in TypeScript, you can use JSON.parse().
Example 1 – Parse JSON String
In this example, we will take a JSON string and parse it.
example.ts
let jsonStr: string = '{"name":"TutorialKart", "property":"Website"}' let jsonObj = JSON.parse(jsonStr) let name: string = jsonObj.name let property: string = jsonObj.property console.log(name) console.log(property)
Output
TutorialKart Website
ADVERTISEMENT
Example 2 – Parse JSON String to TypeScript Class Object
In this example, we will take a JSON string and parse it to a TypeScript class object.
example.ts
interface Website { domain: string; extension: number; } let jsonStr: string = '{"domain":"TutorialKart", "extension":"com"}' let myWebsite: Website = JSON.parse(jsonStr) console.log(myWebsite.domain) console.log(myWebsite.extension)
The parsed JSON string is loaded to an object of specified TypeScript class. And we can access the properties of class object just like we access the elements of JSON object, using dot operator.
Output
TutorialKart com
Conclusion
In this TypeScript Tutorial, we learned how to parse a JSON string to a JSON object or to a custom TypeScript class object.