Sometimes, we want to parse a JSON object to a TypeScript object.
In this article, we’ll look at how to parse a JSON object to a TypeScript object.
How to parse a JSON object to a TypeScript object?
To parse a JSON object to a TypeScript object, we use the JSON.parse
method.
For instance, we write
interface Employee {
departmentId: number;
permissionsId: number;
maxWorkHours: number;
employeeId: number;
firstName: string;
lastName: string;
}
const jsonObj: any = JSON.parse(employeeString);
const employee: Employee = <Employee>jsonObj;
to define the Employee
interface.
Then we call JSON.parse
with the employeeStrigng
JSON object string to parse it.
Next, we assign the jsonObj
object to employee
to and use <Employee>
to cast it to an Employee
object.
Conclusion
To parse a JSON object to a TypeScript object, we use the JSON.parse
method.