DEV Community

Imad Uddin
Imad Uddin

Posted on

How to Read a JSON File in JavaScript — Fetch API, Node.js & ES6 Imports

The approach depends entirely on where your code runs. This is the part that trips up most beginners.

In the Browser — use Fetch API

async function loadData() {
  try {
    const response = await fetch('./data.json');
    if (!response.ok) throw new Error(`Status: ${response.status}`);
    const data = await response.json();
    console.log(data);
  } catch (err) {
    console.error("Failed to load JSON:", err.message);
  }
}

loadData();
Enter fullscreen mode Exit fullscreen mode

⚠️ Browsers can't read files directly from disk. The JSON file must be served via a web server or local dev server.

In Node.js — use fs module

const fs = require("fs");

const raw = fs.readFileSync("./data.json", "utf8");
const data = JSON.parse(raw);
console.log(data);
Enter fullscreen mode Exit fullscreen mode

Async version (recommended for large files):

const fs = require("fs/promises");

async function load() {
  const raw = await fs.readFile("./data.json", "utf8");
  const data = JSON.parse(raw);
  console.log(data);
}
Enter fullscreen mode Exit fullscreen mode

ES6 static import (Node 17.5+ / bundlers)

import data from './data.json' assert { type: 'json' };
console.log(data);
Enter fullscreen mode Exit fullscreen mode

Common errors

Error Cause
SyntaxError: Unexpected token Malformed JSON
Failed to fetch File not on a server
ENOENT: no such file Wrong file path in Node

Full guide with large file handling and advanced patterns: How to Read a JSON File in JavaScript

Need to merge or split JSON files? Try the free JSON Merger and JSON Splitter tools.

Top comments (0)