How to Read a JSON File in TypeScript

With TypeScript 2.9 and the introduction of the resolveJsonModule compiler option, you can directly import JSON modules in TypeScript, which is a much more elegant approach than reading the file via the filesystem. This approach also provides type-safety and intellisense benefits.

Here’s how your tsconfig.json file looks like this:

{
  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs",
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "moduleResolution": "node",
  },
  "exclude": [
    "node_modules",
    "dist"
  ]
}

How to Read a JSON File in TypeScript

To read a JSON file in TypeScript, you can use the “fs (filesystem)” module of Node.js.

Here is the step-by-step guide to read a json file in TypeScript:

Step 1: Importing the “fs” Module

When working with Node.js in TypeScript, you can use the “fs” module to read and write files. The “fs” module provides asynchronous and synchronous methods for working with the file system.

To use the fs module in TypeScript, import it at the top of your file:

import * as fs from 'fs';

The * character is used to import all the methods from the fs module.

Step 2: Create a data.json file

In real life, you don’t need to create a json file, but since I am writing this article and don’t have any json file, I need to create it!

[
  {
    "name": "Krunal",
    "age": 30
  },
  {
    "name": "Ankit",
    "age": 28
  }
]

Step 3: Reading and Parsing JSON Data

To read a file in Node.js, use the “fs.readFileSync()” method synchronously. This method returns the raw content of the file as a string.

The JSON.parse() method is used to convert the raw string content (which is expected to be in JSON format) into a JavaScript object.

import * as fs from 'fs';

interface Person {
  name: string;
  age: number;
}

// Read the JSON file and parse it
const readJSONFile = (filename: string): Person => {
  const rawData = fs.readFileSync(filename, 'utf-8');
  return JSON.parse(rawData);
}

const data: Person = readJSONFile('data.json');
console.log(data);

Output

Read a JSON File in TypeScript

Ensure the file data.json exists in the directory from which you’re running the script and contains valid JSON data that matches the Person interface.

Remember to handle potential errors such as the file not being found or an invalid JSON format.

Adding a try-catch block around file reading and parsing operations can help manage these potential issues gracefully.

This approach is much cleaner and more TypeScript-idiomatic than reading the file through the Node.js filesystem API, especially when dealing with configuration files or static data that’s part of your project.

That’s it!

Leave a Comment