How to read JSON file in JavaScript?

There are three effective methods to read JSON files in JavaScript using fetch(), import statements, and require(). This article covers practical examples for both browser and Node.js environments.

JSON (JavaScript Object Notation) is a lightweight data interchange format that's easy for humans to read and write. In this article, we'll explore three different approaches to reading JSON files in JavaScript:

Approaches to Read JSON file

Each method has its use cases and considerations, so let's dive into each approach.

Sample JSON File

This will be our JSON file (data.json). We'll use this same file in all three approaches:

{
    "users": [
        {
            "site": "Tutorialspoint",
            "user": "Simple and Easy Learning"
        }
    ]
}

Using the fetch() Method (Browser)

The fetch() method is a modern way to make network requests in JavaScript. It's widely supported in browsers and works with files served from a web server.

// File name data.json served from a web server
fetch('./data.json')
    .then(response => response.json())
    .then(data => {
        console.log(data);
        console.log(data.users[0].site); // Access specific property
    })
    .catch(error => {
        console.error('Error loading JSON:', error);
    });
{users: [{site: "Tutorialspoint", user: "Simple and Easy Learning"}]}
Tutorialspoint

Note: This method requires the JSON file to be served from a web server due to CORS restrictions. It won't work with local file:// URLs.

Using the import Statement (ES6 Modules)

The import statement allows you to import JSON files directly as modules in modern JavaScript environments. This works in modern browsers and Node.js 17.5+.

// Add "type": "module" to package.json or use .mjs extension
import data from './data.json' assert { type: 'json' };

console.log('Imported data:', data);
console.log('Site name:', data.users[0].site);
console.log('User info:', data.users[0].user);
Imported data: { users: [ { site: 'Tutorialspoint', user: 'Simple and Easy Learning' } ] }
Site name: Tutorialspoint
User info: Simple and Easy Learning

Requirements: Add "type": "module" to your package.json or use .mjs file extension.

Using the require() Method (Node.js)

The require() function is the traditional CommonJS way to import modules in Node.js. It automatically parses JSON files and returns the parsed object.

const data = require('./data.json');

console.log('Loaded data:', data);
console.log('Number of users:', data.users.length);
console.log('First user:', data.users[0]);
Loaded data: { users: [ { site: 'Tutorialspoint', user: 'Simple and Easy Learning' } ] }
Number of users: 1
First user: { site: 'Tutorialspoint', user: 'Simple and Easy Learning' }

Method Comparison

Method Environment Asynchronous Use Case
fetch() Browser Yes Remote/server files
import Modern JS/Node.js No ES6 modules
require() Node.js No CommonJS modules

Error Handling Best Practices

// Using try-catch with require()
try {
    const data = require('./data.json');
    console.log('Data loaded successfully:', data);
} catch (error) {
    console.error('Failed to load JSON file:', error.message);
}
Data loaded successfully: { users: [ { site: 'Tutorialspoint', user: 'Simple and Easy Learning' } ] }

Conclusion

Choose the appropriate method based on your environment: use fetch() for browser-based applications with server files, import for modern ES6 modules, and require() for traditional Node.js applications. Always implement proper error handling when working with file operations.

Updated on: 2026-03-15T23:19:00+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements