Convert TypeScript Objects to JSON

While creating TypeScript-based web apps, you’ll often need to convert objects into JSON for sending data to APIs, saving it in local storage, or logging structured output. Although JSON.stringify usually works fine, it can be difficult when your objects have dates, functions, or special types.

In this tutorial, we’ll learn how to convert TypeScript objects to JSON, handle common edge cases, and apply best practices to keep your data clean and usable.

Understanding JSON and TypeScript

JSON is a text format that is completely language-independent but uses conventions familiar to programmers of the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

TypeScript, on the other hand, is a statically typed superset of JavaScript that compiles to plain JavaScript. It provides optional static typing, classes, and interfaces, which can help catch errors early in the development process.

Why Convert TypeScript Objects to JSON?

There are several reasons why you might need to convert TypeScript objects to JSON:

  1. Data Storage: JSON is commonly used for storing data in databases.
  2. Data Transmission: JSON is frequently used for transmitting data between a server and a web application.
  3. Configuration Files: JSON is often used for configuration files because it is easy to read and write.

Check out: Optional Parameters in TypeScript Interfaces

Converting TypeScript Objects to JSON

Let’s start with the basics. The most straightforward way to convert a TypeScript object to JSON is by using the JSON.stringify method, which is built into JavaScript and, by extension, available in TypeScript.

Basic Example

Consider a simple TypeScript object representing a person:

interface Person {
    firstName: string;
    lastName: string;
    age: number;
    address: {
        street: string;
        city: string;
        state: string;
        zipCode: string;
    };
}

const person: Person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    address: {
        street: "123 Main St",
        city: "Anytown",
        state: "CA",
        zipCode: "12345"
    }
};

const jsonString = JSON.stringify(person);
console.log(jsonString);

In this example, the person object is converted to a JSON string using JSON.stringify. The output will be:

{
    "firstName": "John",
    "lastName": "Doe",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zipCode": "12345"
    }
}

Output:

Convert Json to object in Typescript

Check out: How to Convert JSON to TypeScript Interface?

Handling Complex Objects

When dealing with more complex objects, such as those containing methods or non-serializable properties, you need to handle these cases explicitly. Methods and undefined properties are not included in the JSON output.

Consider the following example:

interface Employee {
    name: string;
    position: string;
    salary: number;
    hireDate: Date;
    getFullName: () => string;
}

const employee: Employee = {
    name: "Keeth Williams",
    position: "Software Tester",
    salary: 200000,
    hireDate: new Date("2025-01-15"),
    getFullName: function () {
        return this.name;
    }
};

const jsonString = JSON.stringify(employee);
console.log(jsonString);

Output:

TypeScript Object to Json conversion

In this case, the getFullName method and the hireDate property will not be included in the JSON output because functions and non-serializable properties like Date are not supported by JSON.

Custom Serialization

To include properties that are not natively supported by JSON, you can define a custom serialization function. For example, to serialize the hireDate property as a string, you can use a custom replacer function:

const jsonString = JSON.stringify(employee, (key, value) => {
    if (key === "hireDate" && value instanceof Date) {
        return value.toISOString();
    }
    if (typeof value === "function") {
        return undefined;
    }
    return value;
});

console.log(jsonString);

The output will now include the hireDate as a string:

{
    "name": "Keeth Williams",
    "position": "Software Tester",
    "salary": 200000,
    "hireDate": "2025-01-15T00:00:00.000Z"
}

Output:

Convert object to json in typescript

Check out: Create an Object from an Interface in TypeScript

Nested Objects and Arrays

TypeScript objects can also contain nested objects and arrays. The JSON.stringify method handles these cases automatically.

Consider an example with nested objects and arrays:

interface Company {
    name: string;
    employees: Employee[];
}

const company: Company = {
    name: "TechCorp",
    employees: [
        {
            name: "Jane Smith",
            position: "Software Engineer",
            salary: 120000,
            hireDate: new Date("2025-01-15"),
            getFullName: function () {
                return this.name;
            }
        },
        {
            name: "John Doe",
            position: "Product Manager",
            salary: 130000,
            hireDate: new Date("2025-04-01"),
            getFullName: function () {
                return this.name;
            }
        }
    ]
};

const jsonString = JSON.stringify(company, (key, value) => {
    if (key === "hireDate") {
        return value.toISOString();
    }
    if (typeof value === "function") {
        return undefined;
    }
    return value;
});
console.log(jsonString);

The output will be:

{
    "name": "TechCorp",
    "employees": [
        {
            "name": "Jane Smith",
            "position": "Software Engineer",
            "salary": 120000,
            "hireDate": "2025-01-15T00:00:00.000Z"
        },
        {
            "name": "John Doe",
            "position": "Product Manager",
            "salary": 130000,
            "hireDate": "2025-04-01T00:00:00.000Z"
        }
    ]
}

Output:

Converting TypeScript Objects to JSON

Best Practices for JSON Serialization in TypeScript

1. Use Interfaces for Type Safety

Always define interfaces for your objects to ensure type safety. This helps catch errors early and makes your code more maintainable.

2. Handle Dates and Functions Explicitly

Since JSON does not support dates and functions, you need to handle these cases explicitly using custom serialization functions.

3. Avoid Circular References

Be cautious of circular references in your objects, as JSON.stringify will throw an error if it encounters a circular reference. You can use libraries like circular-json to handle such cases.

4. Use Third-Party Libraries for Complex Cases

For more complex serialization needs, consider using third-party libraries like class-transformer or io-ts. These libraries provide advanced features for serializing and deserializing TypeScript objects.

For example, class-transformer can be used to handle complex serialization scenarios:

import { plainToClass, classToPlain } from 'class-transformer';

class User {
    firstName: string;
    lastName: string;
    age: number;
    hireDate: Date;

    constructor(firstName: string, lastName: string, age: number, hireDate: Date) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.hireDate = hireDate;
    }
}

const user = new User("Emily", "Johnson", 25, new Date("2025-03-10"));
const jsonString = JSON.stringify(classToPlain(user));
console.log(jsonString);

Output:

How to convert object to json in TypeScript

Conclusion

In this TypeScript tutorial, we have learned how to convert TypeScript objects to JSON using JSON.stringify. While it works well for simple objects, it can run into issues when handling dates, functions, or other non-serializable values.

We explored how to use a custom replacer function to manage these special cases and saw examples involving nested objects and arrays.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.