TypeScript - Parse JSON String - Tutorial Kart

TypeScript ? Parse JSON String

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

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.

TypeScript

TypeScript Tutorial TypeScript Variables TypeScript if TypeScript if-else TypeScript Switch TypeScript For Loop TypeScript While Loop TypeScript Do-While Loop TypeScript Arrays TypeScript Tuples TypeScript Unions TypeScript Functions TypeScript Anonymous Functions

TypeScript Object Oriented Concepts

TypeScript Class TypeScript Inheritance TypeScript Method Overriding TypeScript Interface

TypeScript String Operations

TypeScript String Length TypeScript String Split

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download