How to Convert TypeScript Objects to JSON [5 Practical Methods]

Working with TypeScript and JSON is something I do almost daily in my development work. Recently, while building a React application that needed to send data to an API, I had to convert TypeScript objects to JSON format.

In this tutorial, I’ll guide you through various methods for converting TypeScript objects to JSON, including handling complex types and custom serialization. So let’s dive in!

Understanding TypeScript Objects vs. JSON

Before we jump into the conversion process, it’s important to understand the difference between TypeScript objects and JSON.

TypeScript objects can contain methods, complex types, and references that don’t have direct JSON equivalents.

JSON (JavaScript Object Notation) is a string representation that only supports simple data types like strings, numbers, booleans, arrays, objects, and null.

Method 1: Using JSON.stringify()

The simplest and most common way to convert a TypeScript object to JSON is using the JSON.stringify() method.

// Define a TypeScript interface
interface Customer {
  id: number;
  name: string;
  isActive: boolean;
  orders?: number[];
}

// Create an object based on that interface
const customer: Customer = {
  id: 1001,
  name: "Sarah Johnson",
  isActive: true,
  orders: [4532, 6721, 9053]
};

// Convert to JSON
const customerJSON = JSON.stringify(customer);
console.log(customerJSON);
// Output: {"id":1001,"name":"Sarah Johnson","isActive":true,"orders":[4532,6721,9053]}

This method works well for simple objects but has limitations with complex types.

I executed the above TypeScript code using VS Code; you can see the exact output in the screenshot below:

Convert TypeScript Objects to JSON

Check out How to Import JSON Files in TypeScript?

Method 2: Using JSON.stringify() with Replacer Function

If you need more control over how properties are serialized, you can use a replacer function:

interface Employee {
  id: number;
  name: string;
  hireDate: Date;
  department: string;
  salary: number;
}

const employee: Employee = {
  id: 5238,
  name: "Michael Rodriguez",
  hireDate: new Date("2021-03-15"),
  department: "Engineering",
  salary: 120000
};

// Use a replacer to format the date and exclude salary
const employeeJSON = JSON.stringify(employee, (key, value) => {
  if (key === "hireDate" && value instanceof Date) {
    return value.toISOString().split('T')[0]; // Format date as YYYY-MM-DD
  }
  if (key === "salary") {
    return undefined; // Exclude salary from JSON
  }
  return value;
});

console.log(employeeJSON);
// Output: {"id":5238,"name":"Michael Rodriguez","hireDate":"2021-03-15","department":"Engineering"}

The replacer function is powerful for customizing how your data is serialized.

You can see the exact output in the screenshot below:

How to Convert TypeScript Objects to JSON

Check out How to Compare String to Enum in TypeScript

Method 3: Using a Custom toJSON Method

TypeScript objects can implement a toJSON method that automatically gets called by JSON.stringify():

class Product {
  id: number;
  name: string;
  price: number;
  inventory: number;
  lastUpdated: Date;

  constructor(id: number, name: string, price: number, inventory: number) {
    this.id = id;
    this.name = name;
    this.price = price;
    this.inventory = inventory;
    this.lastUpdated = new Date();
  }

  // Custom serialization logic
  toJSON() {
    return {
      id: this.id,
      name: this.name,
      price: `$${this.price.toFixed(2)}`,
      inStock: this.inventory > 0,
      lastUpdated: this.lastUpdated.toISOString()
    };
  }
}

const product = new Product(7890, "Wireless Headphones", 149.99, 25);
const productJSON = JSON.stringify(product);

console.log(productJSON);
// Output: {"id":7890,"name":"Wireless Headphones","price":"$149.99","inStock":true,"lastUpdated":"2023-11-05T15:30:45.123Z"}

This approach is excellent when you need consistent serialization logic for specific types.

Check out How to Convert TypeScript Enum to Number

Method 4: Handle Circular References

One common issue when converting objects to JSON is dealing with circular references. Here’s how to handle them:

interface Department {
  name: string;
  manager?: Employee;
  employees: Employee[];
}

interface Employee {
  name: string;
  department?: Department;
}

// Create objects with circular references
const engineering: Department = {
  name: "Engineering",
  employees: []
};

const alice: Employee = {
  name: "Alice Smith",
  department: engineering
};

engineering.manager = alice;
engineering.employees.push(alice);

// This would cause an error:
// const jsonWithError = JSON.stringify(engineering);
// TypeError: Converting circular structure to JSON

// Solution: Track processed objects
function circularReplacer() {
  const seen = new WeakSet();
  return (key: string, value: any) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) {
        return "[Circular Reference]";
      }
      seen.add(value);
    }
    return value;
  };
}

const safeJSON = JSON.stringify(engineering, circularReplacer());
console.log(safeJSON);

This approach safely handles circular references that would otherwise cause errors.

Read How to Push Objects into an Array in TypeScript?

Method 5: Using Type Transformers for Complex Objects

For complex objects with custom types, you might want to create transformer functions:

// Complex type with a Map
interface UserSettings {
  userId: number;
  preferences: Map<string, any>;
  lastLogin: Date;
}

// Create a user settings object
const settings: UserSettings = {
  userId: 4217,
  preferences: new Map([
    ["theme", "dark"],
    ["notifications", { email: true, push: false }],
    ["language", "en-US"]
  ]),
  lastLogin: new Date()
};

// Transform function for UserSettings
function transformUserSettings(settings: UserSettings): any {
  return {
    userId: settings.userId,
    preferences: Array.from(settings.preferences.entries())
      .reduce((obj, [key, value]) => {
        obj[key] = value;
        return obj;
      }, {} as Record<string, any>),
    lastLogin: settings.lastLogin.toISOString()
  };
}

const settingsJSON = JSON.stringify(transformUserSettings(settings));
console.log(settingsJSON);
// Output: {"userId":4217,"preferences":{"theme":"dark","notifications":{"email":true,"push":false},"language":"en-US"},"lastLogin":"2023-11-05T15:45:22.543Z"}

This method gives you complete control over the transformation process.

Check out How To Get String Between 2 Characters In TypeScript?

Parsing JSON Back to TypeScript Objects

After sending and receiving JSON, you often need to convert it back to TypeScript objects:

// Parse JSON string back to an object
const customerData = '{"id":1001,"name":"Sarah Johnson","isActive":true,"orders":[4532,6721,9053]}';
const parsedCustomer = JSON.parse(customerData) as Customer;

// For dates and other complex types, you may need to transform the parsed object
const employeeData = '{"id":5238,"name":"Michael Rodriguez","hireDate":"2021-03-15","department":"Engineering"}';
const parsedEmployee = JSON.parse(employeeData);

// Convert string date back to Date object
parsedEmployee.hireDate = new Date(parsedEmployee.hireDate);

console.log(parsedEmployee.hireDate instanceof Date); // true

Remember that JSON.parse() doesn’t automatically convert string dates back to Date objects or handle other complex types.

Check out Replace String In JSON File Using PowerShell

Best Practices for TypeScript Object to JSON Conversion

After years of working with TypeScript and JSON, I’ve developed these best practices:

  1. Type Safety: Always use TypeScript interfaces or types to ensure your objects have the expected structure.
  2. Handle Complex Types: Be mindful of properties that don’t serialize well (like Dates, Maps, Sets) and provide custom serialization for them.
  3. Security: Be cautious about what data you serialize to JSON, especially when dealing with sensitive information.
  4. Performance: For large objects, consider serializing only the properties you need rather than the entire object.
  5. Error Handling: Always wrap your JSON conversion in try-catch blocks when working with user-provided data.

Conclusion

In this tutorial, I explained how to convert TypeScript objects to JSON using various methods such as JSON.stringify().

If you have any questions about TypeScript object to JSON conversion or encounter any specific challenges, feel free to leave a comment below!

You may also like the following tutorials:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App