How to Convert JSON to Array in TypeScript?

One of my team members recently asked about converting JSON to array in TypeScript. There are various methods to do this. In this tutorial, I will explain how to convert JSON to an array in TypeScript using various methods with examples.

JSON (JavaScript Object Notation) is a lightweight data-interchange format that’s easy for humans to read and write and easy for machines to parse and generate. TypeScript, a superset of JavaScript, adds static types to the language, making it easier to manage and debug code. Converting JSON to an array in TypeScript involves parsing the JSON string and mapping it to the appropriate TypeScript types.

Why Convert JSON to Array in TypeScript?

When working with APIs, you often receive data in JSON format. Converting this data into an array of TypeScript objects allows you to leverage TypeScript’s type-checking and autocompletion features, leading to more robust and maintainable code. This is particularly useful in large applications where data integrity and type safety are crucial.

Convert JSON to Array in TypeScript

Let’s start with a simple example. Imagine you are working with a JSON response from an API that provides a list of users. Here’s a sample JSON string:

[
  {
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@example.com"
  },
  {
    "id": 2,
    "name": "Jane Smith",
    "email": "jane.smith@example.com"
  }
]

Step 1: Define TypeScript Interfaces

First, define an interface that matches the structure of the JSON objects. This helps TypeScript understand the shape of the data and provides type-checking.

interface User {
  id: number;
  name: string;
  email: string;
}

Step 2: Parse the JSON String

Next, use the JSON.parse method to convert the JSON string into an array of objects. TypeScript will automatically infer the type based on the interface you defined.

const jsonString = `[
  {
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@example.com"
  },
  {
    "id": 2,
    "name": "Jane Smith",
    "email": "jane.smith@example.com"
  }
]`;

const users: User[] = JSON.parse(jsonString);
console.log(users);

Step 3: Validate the Data

While JSON.parse is a powerful tool, it doesn’t perform any type-checking or validation. You might want to validate the data to ensure it conforms to the expected structure. One way to do this is by using a runtime type-checking library like io-ts or writing custom validation functions.

Here is the complete code:

[
  {
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@example.com"
  },
  {
    "id": 2,
    "name": "Jane Smith",
    "email": "jane.smith@example.com"
  }
]
interface User {
  id: number;
  name: string;
  email: string;
}
const jsonString = `[
  {
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@example.com"
  },
  {
    "id": 2,
    "name": "Jane Smith",
    "email": "jane.smith@example.com"
  }
]`;

const users: User[] = JSON.parse(jsonString);
console.log(users);

I executed the above TypeScript code and you can see the exact output in the screenshot below:

Min() function in python

Read Remove Undefined Values from an Array in TypeScript

Advanced Example: Fetching Data from an API

In a real-world scenario, you often fetch JSON data from an API. Let’s modify our example to fetch user data from a hypothetical API endpoint.

Step 1: Fetch Data Using fetch

Use the fetch API to get the JSON data from the server. This example uses the async/await syntax for better readability.

async function fetchUsers(): Promise<User[]> {
  const response = await fetch('https://api.example.com/users');
  const data = await response.json();
  return data as User[];
}

fetchUsers().then(users => {
  console.log(users);
});

Step 2: Error Handling

Always include error handling when working with asynchronous operations. This ensures your application can gracefully handle failures.

async function fetchUsers(): Promise<User[]> {
  try {
    const response = await fetch('https://api.example.com/users');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    return data as User[];
  } catch (error) {
    console.error('Failed to fetch users:', error);
    return [];
  }
}

fetchUsers().then(users => {
  console.log(users);
});

Read Sort an Array Alphabetically in TypeScript

Working with Complex JSON Structures

Sometimes, the JSON data you receive is more complex, with nested objects or arrays. Let’s consider an example where each user has an array of addresses.

[
  {
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@example.com",
    "addresses": [
      {
        "street": "123 Main St",
        "city": "New York",
        "state": "NY",
        "zip": "10001"
      }
    ]
  },
  {
    "id": 2,
    "name": "Jane Smith",
    "email": "jane.smith@example.com",
    "addresses": [
      {
        "street": "456 Elm St",
        "city": "Los Angeles",
        "state": "CA",
        "zip": "90001"
      }
    ]
  }
]

Step 1: Define Nested Interfaces

Extend the User interface to include the nested Address objects.

interface Address {
  street: string;
  city: string;
  state: string;
  zip: string;
}

interface User {
  id: number;
  name: string;
  email: string;
  addresses: Address[];
}

Step 2: Parse the JSON String

Parse the JSON string as before, and TypeScript will handle the nested structures.

const jsonString = `[
  {
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@example.com",
    "addresses": [
      {
        "street": "123 Main St",
        "city": "New York",
        "state": "NY",
        "zip": "10001"
      }
    ]
  },
  {
    "id": 2,
    "name": "Jane Smith",
    "email": "jane.smith@example.com",
    "addresses": [
      {
        "street": "456 Elm St",
        "city": "Los Angeles",
        "state": "CA",
        "zip": "90001"
      }
    ]
  }
]`;

const users: User[] = JSON.parse(jsonString);
console.log(users);

Read Remove Duplicates from an Array in TypeScript

Best Practices for Converting JSON to Array in TypeScript

Here are some best practices you can follow while converting JSON to array in TypeScript.

Use Type Assertions Carefully

Type assertions can be useful, but they should be used cautiously. Overusing type assertions can lead to runtime errors if the data doesn’t match the expected structure. Always validate your data where possible.

Leverage TypeScript’s Type System

Define interfaces and types for your data structures to take advantage of TypeScript’s type-checking capabilities fully. This will make your code more readable and less prone to errors.

Handle Errors Gracefully

When working with external data sources, error handling should always be included to manage network failures, invalid data, and other potential issues.

Keep Your Code DRY (Don’t Repeat Yourself)

If you find yourself writing similar code for parsing and validating JSON data, consider creating reusable functions or utility classes. This will reduce code duplication and make your codebase easier to maintain.

Conclusion

In this tutorial, I explained how to convert JSON to an array in TypeScript using various methods with examples. By defining appropriate interfaces, using JSON.parse, and incorporating proper error handling, you can efficiently manage JSON data in your TypeScript applications.

You may also like:

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.