How to Convert JSON Object to Interface or class in typescript?

Convert JSON to Object Interface: This post talks about different ways of converting json to interface in typescript.

During development, data comes from the REST API in the format of JSON format, So you need to write a code to convert the JSON to interface or class object in typescript.

We are going to learn various ways of converting JSON objects to Interface/class. In my previous article, Learned how to declared and implement typescript interfaces.

This JSON object needs to transfer to the interface/class to bind this data to UI.

Interfaces are used for type checking at compilation, and do not exist at runtime, no implementation but it has contracts and rules, where classes or objects that implement this interface should follow it.

This conversion is required to know as Front applications coded in typescript and calls REST API that interns call backend services, and returns the response in JSON format.

How to Convert json to Object or interface in typescript?

To convert JSON to the interface, the developer does not need to do anything. simply write code that follows some rules to allow the typescript compiler to do the conversion. First, the Interface is defined with properties the same as JSON fields.

It is not required to match all fields in a JSON object with interfaces, But

  • Interface fields are a subset of the JSON object
  • Interface field names and types should match with object data

We have two ways of converting.

  • Implicit interface conversion
  • Explicit interface conversion

Implicit interface conversion

The developer will not write any code to do the conversion. just follow the guidelines above and the Typescript compiler will do it automatically

Here is an example using the Implicit conversion approach

The function returns Employee data.

function getEmployees(): Array {
  return [
    { id: 1, name: "john", salary: 50000 },
    { id: 2, name: "Kiran", salary: 40000 },
  ];
}

Here is the sequence of steps to follow

  • The interface should be created like the below using the interface keyword.
  • Declared interface with three properties, It is not compulsory to declare all properties.
  • You can declare two fields also as per your requirement, but property names should match with the name of JSON object keys
  • Each JSON object represents an Employee Object. if the JSON object is a list of arrays, Then in your app you should map it to an Array of employees or Employee[]

Here is an interface declared in Employee.ts.

interface Employee {
  id: number;
  name: string;
  salary: number;
}

Typescript Explicit Interface conversion

In this, The developer will write code to convert to the interface.

It is useful when customizing or processing data before converting it to interfaces or classes.

Using first-class functions - the array’s method map(), iterates through the JSON object array and maps the elements to the interface, as shown in the code below.

const emps = [
        { 'id': 1, 'name': 'john', 'salary': 50000 },
        {'id': 2, 'name': 'Kiran', 'salary': 40000}
    ];
const empsClass: Employee = emps.map(obj => {
  id: obj.Id,
  name: obj.Name
});
interface Employee {
    id: number,
    name: string,
    salary: number
}

How to map a Nested JSON object to interface in typescript?

Suppose a nested JSON object structure Here, Declared array of objects, where each object contains a nested object

const emps = [{
        'id': 1,
        'name': 'john',
        'salary': 50000,
        "address": {
            "colony": "John Road",
            "state": "NewYork",
            "country": "USA"
        }
    },
    {
        'id': 2,
        'name': 'Kiran',
        'salary': 40000 "address": {
            "colony": "Stree 12",
            "state": "NewYork",
            "country": "USA"
        }
    }
];

Define the Interface based on the above JSON structure.

  • employee is an interface, address field contains another interface address. It is a one-to-one mapping.
  • Created two interfaces one for employee and another for address
  • Declared mapping address in employee interface using normal data type declaration.’
  • The same implicit interface mapping rules apply here to declare the address interface.
interface Employee {
    id: number,
    name: string,
    salary: number,
    address: Address
}

interface Address {
    colony: string,
    state: string,
    country: string,
}

Custom JSON objects, such as recursive JSON types or tree model data, are used in this approach. Each parent contains children.

We have seen all the above examples with interfaces. You can also parse JSON to classes using a similar approach.

Convert JSON to Interface with Optional Fields

Sometimes, if data is coming from backend APIs, some fields in the JSON structure are optional.

if the field in JSOn is optional, Interface properties must be suffixes with the ? question mark operator.

Below example, the Department is optional

interface Employee {
  id: number;
  name: string;
  salary: number;
  department?: string; // department is optional
}

department field in the incoming json data is not present as an optional.

const emp = {
  id: 1,
  name: "john",
  salary: 50000,
};

Convert JSON to Interface with dynamic fields

if JSON contains a dynamic or unknown field structure, Then we can use this approach.

{
  "status": 200,
  "message": "success"
  "result": {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"

  }
}

Next, the Interface can be declared as follows

Interface contains a dynamic field declared as any type:

any represents any data of valid typescript types.

interface data{
  status: number;
  message: string;
  result: any;
}

use interface with index signature:

index signature allows you to define a contract with dynamic keys, declared with [] with declaration of types. It allows you to declare a field in which you don’t know the structure of data.

interface data{
  status: number;
  message: string;
  result: {
    [key: string]: string;
  };}

Convert JSON to Interface with other field types

You can declare another field such as union type, date, and enum as follows for converting JSOn data into the interface.

JSOn with union fields

In this, the JSOn field contains a field of one type from multiple fields.

{
  "id": 1,
  "name": "john",
  "salary": "4000"
}

salary field of Employe is a either string or a number.

interface Employee {
  id: number;
  name: string;
  salary: string | number;
}
  • JSON with date fields
{
  "id": 1,
  "name": "john",
  "salary": "4000",
  "createDate": "2024-01-01T00:00:00Z"
}

Interface field declared with Date field.

interface Employee {
  id: number;
  name: string;
  salary: string | number;
  createDate: Date;
}
  • JSON with Enum-type fields
{
  "id": 1,
  "name": "john",
  "salary": "4000",
  "createDate": "2024-01-01T00:00:00Z",
  "status": "Active"
}

Interface field declared with Enum type Status field.

enum Status {
  Active = "Active",
  Disable = "Disable",
}

interface Employee {
  id: number;
  name: string;
  salary: string | number;
  createDate: Date;
  status: Status;
}

Summary

To summarize, Learned multiple ways to convert JSON to object or interface. You can select one approach based on your needs.