15 min read read
how to read json file in javascriptjavascript read jsonnode.js read json filefetch api json exampleread local json file javascriptimport json javascript es6json.parse javascriptread json from url javascripthandling json errors javascriptjson tutorialweb developmentnode.js tutorial

How to Read JSON File in JavaScript: A Complete Step by Step Guide

Imad Uddin

Full Stack Developer

How to Read JSON File in JavaScript: A Complete Step by Step Guide

Junior developer's first week assignment: build dynamic dashboard. Data existed in simple data.json file. Hours spent attempting to "open" it like normal variable.

Tried everything. Basic script tags. Unusual hacks. Eventually understood fundamental difference between browser environment and server. That realization revealed reading JSON files in JavaScript extends beyond syntax. Requires understanding data flow through modern web.

JSON (JavaScript Object Notation) dominates data exchange today. Fetching weather data from public API. Reading configuration settings in Node.js backend. Processing user-uploaded files. JSON operations occur constantly.

This guide covers every reliable method for reading and parsing JSON files. Both browser and Node.js ecosystems included. Advanced territory: memory-safe streams for massive datasets and modern ES6 import assertions.

Why JSON Has Become the Industry Standard

Understanding motivation precedes technical implementation.

Worked with XML: verbose and difficult manual parsing. JSON provides contrast. Lightweight format. Maps perfectly to JavaScript objects.

Common JSON reading scenarios:

API Integration:

Fetching dynamic content from RESTful services. Product lists or user profiles.

Configuration Management:

Storing application settings in structured format. API keys or theme preferences.

Data Migration:

Reading exported database data for transformation or display.

Local Development:

Using mock data files building frontends before backend readiness.

This article provides capability handling any JSON file. Regardless of location or size. With absolute confidence.

Understanding the Environment: Browser vs. Node.js

The very first thing you must identify is where your code is running. This is the part that trips up most beginners.

  1. The Browser (Client Side): For security reasons, the browser cannot just reach into your "C: Drive" or "Documents" folder and read a file. It can only fetch files via a web server (using a URL) or read files that a user explicitly uploads via an input field.
  2. Node.js (Server Side): Since Node.js runs directly on your operating system, it has full permissions to read, write, and delete files on your hard drive.

I have seen many developers try to use Node.js modules like fs in a React or Vue project, only to be met with a "Module not found" error. Always remember: if it is for the user's browser, use fetch. If it is for a script running on your machine, use fs.


Method 1: Reading JSON in the Browser Using the Fetch API

Fetch API represents modern, standard resource request method in browsers. Built into every modern browser. Completely replaced older, clunky XMLHttpRequest tool.

The Basic Implementation

JSON file sitting on server (example: data.json). Most robust reading method using async/await:

async function loadUserData() {
  try {
    // 1. Start the request
    const response = await fetch('./data.json');

    // 2. Check if the file exists and is accessible
    if (!response.ok) {
      throw new Error(`Could not fetch the file. Status: ${response.status}`);
    }

    // 3. Convert the response body to a JavaScript object
    const data = await response.json();

    // 4. Use your data!
    console.log("User Name:", data.name);
    console.log("User Email:", data.email);
  } catch (error) {
    console.error("Oh no, something went wrong:", error.message);
  }
}

loadUserData();

Deep Insight: Why response.ok Matters

Common mistake: developers skipping response.ok check.

Browser receives 404 Not Found or 500 Server Error: fetch() promise still technically "resolves."

Code attempts parsing error message (often HTML) as JSON. Results in dreaded "Unexpected token < in JSON at position 0" error.

Always verify status before parsing. Prevents cryptic error messages.


Method 2: Modern ES6 JSON Modules (Importing JSON)

Modern JavaScript (2024-2025) supports JSON Modules. Allows treating JSON file almost like regular JavaScript file using import statement.

Perfect for static configuration files or small data sets.

How to Use Import Assertions

Requires with clause (previously called "assertions") telling browser file importing specifically represents JSON file.

// Note the 'with' syntax for JSON modules
import configData from './config.json' with { type: 'json' };

console.log("Application Theme:", configData.theme);
console.log("API Version:", configData.version);

Pros:

Loads before script runs. Makes data immediately available. Clean syntax without needing fetch or await inside main logic.

Cons:

Data cached. JSON file changes on server: browser won't re-fetch unless page reloaded. Not suitable for fetching data from dynamic API endpoint.


Method 3: Reading Local User Files (The File Input Method)

Sometimes allowing user uploading own JSON file to website necessary. Example: building tool like JSON Flattener.

Use FileReader API for this scenario.

const fileInput = document.getElementById('myFileInput');

fileInput.addEventListener('change', (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();

  reader.onload = (e) => {
    try {
      const jsonContent = JSON.parse(e.target.result);
      console.log("File content successfully parsed:", jsonContent);
    } catch (err) {
      alert("This file is not a valid JSON format!");
    }
  };

  reader.readAsText(file);
});

Recommended approach for building utility tools. Fast execution. Secure. Works entirely on user's machine without ever sending data to server.


Method 4: Reading JSON in Node.js (Primary Backend Method)

Server-side work provides multiple JSON handling methods.

Building CLI tool or backend server: fs (File System) module represents primary tool.

Option A: Using fs/promises (The Modern Standard)

Non-blocking, promise-based file reading method. Recommended for almost all modern Node.js applications.

import { readFile } from 'node:fs/promises';

async function getLocalSettings() {
  try {
    const filePath = new URL('./settings.json', import.meta.url);
    const rawData = await readFile(filePath, 'utf8');
    
    // Remember: fs only gives you a string. You MUST parse it.
    const settings = JSON.parse(rawData);
    
    console.log("Merging data...", settings.db_host);
  } catch (error) {
    if (error.code === 'ENOENT') {
      console.error("The file does not exist at the specified path.");
    } else {
      console.error("Syntax Error or Permission Denied:", error.message);
    }
  }
}

Option B: Using require() (Legitimate Shortcut)

Still using CommonJS (traditional Node.js modules) with small static configuration file: "shortcut" using require available.

const localData = require('./data.json');
// No JSON.parse needed! Require handles it automatically.
console.log(localData.items);

Warning:

Advise against using require() for large data files.

Reason: require() caches file in memory. JSON file updated on disk: require() still returns old data until server restart.


Comparison: Which Method is Best for You?

ScenerioTechnologyBest MethodWhy?
Web Page (External Data)Browserfetch()Native, non blocking, and powerful.
Web Page (Bundled Config)BrowserimportClean and easy for build time data.
User Uploaded DataBrowserFileReaderSecurely reads local user files.
Node.js Core BackendNode.jsfs/promisesProfessional, async, and memory safe.
Quick Scripts/ToolsNode.jsrequire()Fastest to write, but careful with caching.

Deep Insight: The "Unexpected Token" Nightmare

If you have spent any time writing JavaScript, you have likely encountered an error like SyntaxError: Unexpected token ' in JSON at position 0.

During my years of managing data at scale, I have found that the problem is rarely your code. It is almost always one of these "invisible" issues:

  1. The BOM (Byte Order Mark): Some text editors add an invisible marker at the start of a UTF8 file. JavaScript's JSON.parse will choke on this. To fix it, ensure your file is saved as "UTF8 without BOM."
  2. Single Quotes: This is the #1 mistake. JSON requires double quotes for keys and string values ("key": "value"). Single quotes ('key': 'value') are valid JavaScript, but they are invalid JSON.
  3. Trailing Commas: JSON does not allow a comma after the last item in an array or object. My advice is to use an online JSON Formatter to clean your data before trying to read it.
  4. The UTF8 Flag: In Node.js, if you forget to pass utf8 as the second argument to readFile, it will return a Buffer (raw binary data) instead of a string. JSON.parse cannot understand a Buffer.

Handling Large JSON Files (The Professional Way)

What happens if you need to read a JSON file that is 5GB? If you try to use JSON.parse() on a 5GB file, your computer will likely run out of memory and the program will crash. This is because JSON.parse() tries to load the entire object into memory at once.

For large files, you must use Streaming. Instead of reading the whole file, you read it piece by piece.

In Node.js, you would use a package like stream json:

const fs = require('fs');
const { chain } = require('stream-chain');
const { parser } = require('stream-json');
const { streamArray } = require('stream-json/streamers/StreamArray');

const pipeline = chain([
  fs.createReadStream('massive-data.json'),
  parser(),
  streamArray()
]);

pipeline.on('data', (data) => {
  // processes one object at a time! Memory stays low.
  console.log('Processing record:', data.value.id);
});

If you are dealing with a large file right now and just need a quick way to handle it, you can also use our JSON File Splitter to break it into smaller pieces that are easier to read.


Best Practices for Reading JSON in Production

After years of building data-intensive applications, I have developed a set of "Golden Rules" for reading JSON:

1. Always Use Try/Catch

Never assume a JSON file is perfect. Even if it was valid yesterday, a bug in another service could corrupt it today. Always wrap your parsing logic in a try...catch block to prevent your entire application from crashing.

2. Validate Your Data (Zod or Joi)

Just because a file is valid JSON does not mean it has the data you expect. If your code expects user.email but the file only contains user.username, your app will crash. Use a validation library like Zod to define a schema and verify the data as soon as you parse it.

3. Be Mindful of CORS

When using fetch() in the browser to read a JSON file from a different domain, you will run into CORS (Cross Origin Resource Sharing) issues. Ensure the server hosting the JSON file has the correct headers (****Access Control Allow Origin: *****) enabled.

4. Encoding is Everything

Always use UTF8 for your JSON files. It is the universal standard. If you are seeing weird symbols or "gibberish" characters where your text should be, it's almost certainly an encoding mismatch. You can use our guide on how to format JSON in Notepad++ to verify and fix encoding issues.


Troubleshooting Common JSON Reading Errors

"Request has been blocked by CORS policy" This is a browser security feature. You cannot fetch a JSON file from domainA.com if you are currently on domainB.com unless the server explicitly allows it. If you're developing locally, use a local server (like the "Live Server" extension in VS Code) rather than opening the HTML file directly as a "file:///" URL.

"Unexpected token < in JSON at position 0" This almost always means you tried to fetch a file that does not exist. The server responded with a 404 Not Found page (which starts with

<html>...
), and the browser tried to parse that HTML as JSON. Check your file path!

"Cannot find module" (in Node.js) If you are using require('./data'), make sure you included the .json extension or that the path is correct relative to the current file. Remember that require paths are relative to the file itself, while fs paths are usually relative to the folder where you started the terminal.


Related Tools and Guides

If you found this guide helpful, check out some of our other developer focused tools and articles:

Final Thoughts

Mastering how to read json file in JavaScript is a rite of passage for every modern developer. Whether you are using the simplicity of fetch(), the power of Node’s fs module, or the modern elegance of ES6 imports, you now have the tools to handle data safely and efficiently.

Next time you are faced with a massive JSON file or a complex API response, remember to check your environment, handle your errors, and keep your memory usage in check. The insight you can gain from well processed data is limitless.

Happy coding!

Read More

All Articles