How to Import a JSON File in Node.js

Node.js is a versatile JavaScript runtime environment that allows you to work with various types of files, including JSON (JavaScript Object Notation) files.

JSON is commonly used for configuration files, data storage, and API responses. In this article, we'll explore how to import a JSON file in Node.js and discuss error handling for a smooth development experience.

Importing JSON Files using require (CommonJS)

Node.js uses the CommonJS module system, and you can use the require function to import JSON files. Here's a step-by-step guide:

  1. Create a JSON File: Start by creating a JSON file, for example, data.json, with some JSON data. This file can contain any JSON-formatted data.

    // data.json
    {
      "name": "John",
      "age": 30,
      "city": "New York"
    }
    
  2. Import the JSON File: In your Node.js script, use the require function to import the JSON data from the file:

    const jsonData = require('./data.json');
    
    console.log(jsonData.name); // Output: John
    console.log(jsonData.age);  // Output: 30
    console.log(jsonData.city); // Output: New York
    

    Make sure to provide the correct relative path to the JSON file in the require statement.

  3. Error Handling: To handle errors that may occur during the file reading process, wrap the require statement in a try...catch block:

    try {
      const jsonData = require('./data.json');
    
      console.log(jsonData.name); // Output: John
      console.log(jsonData.age);  // Output: 30
      console.log(jsonData.city); // Output: New York
    } catch (error) {
      console.error('Error reading JSON file:', error);
    }
    

    This ensures that your application gracefully handles issues with reading JSON files, such as missing or malformed files, and provides meaningful error messages for debugging.

Importing JSON Files using import (ES Modules)

Node.js introduced ES Modules support starting from version 14.13.0. With ES Modules, you can use the import statement to import JSON files. Here's how:

  1. Enable ES Modules: In your project, make sure you have ES Modules enabled by adding "type": "module" to your package.json file:

    // package.json
    {
      "type": "module",
      // ...
    }
    
  2. Create a JSON File: As before, create a JSON file with your data (e.g., data.json).

  3. Import the JSON File: Use the import statement to import the JSON data:

    import jsonData from './data.json';
    
    console.log(jsonData.name); // Output: John
    console.log(jsonData.age);  // Output: 30
    console.log(jsonData.city); // Output: New York
    

    Ensure that you provide the correct relative path to the JSON file in the import statement.

  4. Error Handling: To handle errors when importing JSON files using ES Modules, wrap the import statement in a try...catch block, similar to the CommonJS approach:

    try {
      import jsonData from './data.json';
    
      console.log(jsonData.name); // Output: John
      console.log(jsonData.age);  // Output: 30
      console.log(jsonData.city); // Output: New York
    } catch (error) {
      console.error('Error reading JSON file:', error);
    }
    

Conclusion

Importing JSON files in Node.js is a common task when working with configuration data, API responses, or any JSON-formatted data. You can choose between the CommonJS (require) and ES Modules (import) approaches based on your project's module system and Node.js version.

By adding error handling to your import statements, you ensure that your Node.js application gracefully handles issues with reading JSON files, making it more robust and developer-friendly.