0
0
JavascriptHow-ToBeginner · 4 min read

How to Read JSON File in JavaScript: Simple Guide

To read a JSON file in JavaScript, use the fetch() function in browsers to load and parse the file asynchronously with response.json(). In Node.js, use the fs module's readFileSync or readFile methods and then parse the content with JSON.parse().
📐

Syntax

In browsers, use fetch('file.json').then(response => response.json()) to load and parse JSON asynchronously.

In Node.js, use fs.readFileSync('file.json', 'utf8') to read file content synchronously, then parse it with JSON.parse().

javascript
/* Browser syntax */
fetch('data.json')
  .then(response => response.json())
  .then(data => console.log(data));

/* Node.js syntax */
const fs = require('fs');
const jsonData = fs.readFileSync('data.json', 'utf8');
const data = JSON.parse(jsonData);
console.log(data);
💻

Example

This example shows how to read a JSON file named data.json in a browser using fetch and in Node.js using fs. It prints the parsed JSON object to the console.

javascript
/* Browser example */
fetch('data.json')
  .then(response => response.json())
  .then(data => {
    console.log('Browser JSON data:', data);
  })
  .catch(error => console.error('Error loading JSON:', error));


/* Node.js example */
const fs = require('fs');
try {
  const jsonData = fs.readFileSync('data.json', 'utf8');
  const data = JSON.parse(jsonData);
  console.log('Node.js JSON data:', data);
} catch (err) {
  console.error('Error reading JSON file:', err);
}
Output
Browser JSON data: {"name":"Alice","age":30} Node.js JSON data: { name: 'Alice', age: 30 }
⚠️

Common Pitfalls

  • Trying to read local JSON files with fetch without a server causes CORS errors in browsers.
  • Forgetting to parse JSON text with JSON.parse() in Node.js leads to string data, not objects.
  • Using synchronous file reading (readFileSync) in performance-critical apps can block the event loop.
  • Not handling errors from file reading or JSON parsing causes crashes.
javascript
/* Wrong: Using fetch on local file without server (browser) */
fetch('file.json')
  .then(response => response.json())
  .then(data => console.log(data)); // May fail due to CORS

/* Right: Run a local server or use Node.js fs module */

/* Wrong: Forgetting JSON.parse in Node.js */
const fs = require('fs');
const jsonData = fs.readFileSync('file.json', 'utf8');
console.log(jsonData); // Prints raw string

/* Right: Parse JSON string */
const data = JSON.parse(jsonData);
console.log(data);
📊

Quick Reference

Use this quick guide to remember how to read JSON files in JavaScript environments:

EnvironmentMethodNotes
Browserfetch('file.json').then(r => r.json())Asynchronous, requires server or CORS setup
Node.jsfs.readFileSync('file.json', 'utf8') + JSON.parse()Synchronous, blocks event loop
Node.jsfs.readFile('file.json', 'utf8', callback) + JSON.parse()Asynchronous, preferred for performance

Key Takeaways

Use fetch with response.json() in browsers to read JSON files asynchronously.
In Node.js, read the file content with fs and parse it using JSON.parse().
Avoid reading local files with fetch without a server to prevent CORS errors.
Handle errors when reading or parsing JSON to avoid crashes.
Prefer asynchronous file reading in Node.js for better performance.