Back to blog

How to Read a JSON File in JavaScript (with Examples)

-
Table of contents
-

This lightweight format is one of the most common ways to exchange and store structured data on the web. You’ll see it in APIs, configuration files, mock datasets, and application settings.

If you need to JavaScript read JSON file content in JavaScript, the right method depends mainly on where your code runs. In this guide, we’ll cover the fetch API, FileReader, ES modules, and Node.js tools such as require() and fs.

Understanding JSON in JavaScript

JSON stands for JavaScript Object Notation. It stores information as key-value pairs, arrays, strings, numbers, booleans, and null values. A basic JSON file might look like this:

{
  "name": "Mars",
  "active": true,
  "ports": [8000, 8001, 8002]
}

Although the format looks similar to a regular JavaScript object, the two are not exactly the same. JSON is a text-based data format with strict syntax rules. For example, property names must use double quotes, and the format does not support comments or functions.

Once you load and parse JSON data, JavaScript usually turns it into a normal object or array that you can work with in your code.

How to Read JSON Files in JavaScript

There are several ways to read JSON files, and each one fits a different environment.

In a browser, the fetch API is usually best for files served by a website, while FileReader works with files selected by the user. In modern module-based projects, you can import data directly. In Node.js, require() and the fs module are common choices.

A. Using the Fetch API (Browser)

Fetch API is the easiest method for accessing JSON data from either the same website or a public link. It performs the operation by making an HTTP request and returns a Promise with Response. Using this Response object, you can then get the data by using response.json().

Suppose your project contains this structure:

project/
├── index.html
├── app.js
└── users.json

Your JavaScript file can load users.json like this:

async function loadUsers() {
  try {
    const response = await fetch('./users.json');
 
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
 
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Could not load JSON:', error);
  }
}
 
loadUsers();

The fetch API method first requests the JSON file. The response.ok check catches HTTP errors such as 404 or 500, because fetch() does not automatically reject every unsuccessful HTTP status. Then .json() reads the body and parses the response JSON into usable JSON data.

If the data is being fetched from another domain, then CORS will prevent this. The server must authorize the origin domain with the proper CORS headers. Simply modifying client-side code will not get around the CORS restriction.

For fallback behavior, catch the error and display cached content, an empty state, or a friendly message instead of letting the page fail.

B. Using the FileReader API (Browser, Local Files)

The fetch API cannot freely open arbitrary files from a user’s computer. If someone needs to select a local JSON file, use an <input type="file"> element and the FileReader API.

Your HTML file can contain:

<input type="file" id="jsonFile" accept=".json">
<pre id="output"></pre>

Then use this JavaScript:

const input = document.getElementById('jsonFile');
const output = document.getElementById('output');
 
input.addEventListener('change', () => {
  const file = input.files[0];
  if (!file) return;
 
  const reader = new FileReader();
 
  reader.onload = () => {
    try {
      const data = JSON.parse(reader.result);
      output.textContent = JSON.stringify(data, null, 2);
    } catch (error) {
      output.textContent = 'Invalid JSON file.';
    }
  };
 
  reader.readAsText(file);
});

FileReader reads the selected local JSON file as text. JSON.parse() then converts that string into a JavaScript object.

FileReader only gets access to files the user explicitly selects, which helps protect local files from unrestricted browser access. Its readAsText() method loads the whole file into memory, so it is not ideal for very large files.

Always wrap JSON parse logic in try/catch. A missing comma, extra trailing comma, or broken quote can make the entire JSON file invalid.

C. Using import with ES6 Modules (Modern JS)

Current JavaScript modules can also import data from JSON. In standards-based environments that support JSON modules, the current syntax uses an import attribute:

import settings from './settings.json' with { type: 'json' };
 
console.log(settings);

In Node.js, JSON module imports require the type: 'json' attribute. If your JavaScript file uses a .js extension and you want Node to treat it as an ES module, your package.json can include:

{
  "type": "module"
}

Modern browsers also import these modules using the import attribute, where the JSON file is served using the appropriate JSON MIME type.

Tools like Vite or Next.js could allow importing JSON files using the bundling mechanism of the tool, which means that the syntax could be different depending on your build configuration.

This method is convenient when the JSON file is part of your application source and does not need to change at runtime.

D. Using require() or fs.readFile() in Node.js

Node.js gives you several ways to read JSON files. In a CommonJS project, require() is the shortest:

const fs = require('node:fs');
 
const text = fs.readFileSync('./config.json', 'utf8');
const config = JSON.parse(text);
 
console.log(config);

fs.readFileSync() halts the event loop until the file reading and parsing process is done. This may be okay at the start-up stage, but otherwise asynchronous code would be preferred.

const fs = require('node:fs');
 
fs.readFile('./users.json', 'utf8', (error, text) => {
  if (error) {
    console.error('Read error:', error);
    return;
  }
 
  try {
    const users = JSON.parse(text);
    console.log(users);
  } catch (error) {
    console.error('Invalid JSON:', error);
  }
});

Use asynchronous file access when your application needs to read JSON files without blocking other work.

Common Pitfalls and How to Avoid Them

The first problem is malformed input. Even a small syntax mistake can cause parsing to fail, so validate unfamiliar JSON data and handle exceptions around JSON parse operations.

Another common issue is mixing synchronous and asynchronous code while fetching data or reading from disk. The fetch API, response.json(), FileReader, and fs.readFile() do not return final data immediately. If you try to use the result before the Promise or callback finishes, your code may see undefined values.

It is also easy to confuse a data string with a parsed object. This is a string:

const raw = '{"country":"US"}';

This is parsed data:

const data = JSON.parse(raw);
console.log(data.country);

Finally, take care with large or deeply nested files. Loading an entire JSON file into memory can become expensive. For big datasets, consider streaming, pagination, splitting the dataset, or storing the information in a database instead.

Practical Examples and Use Cases

One simple program for beginners to try is loading the product cards from the JSON file. For example, in the file products.json you will have:

[
  { "name": "Residential Proxies", "type": "Rotating" },
  { "name": "ISP Proxies", "type": "Static" }
]

You can use the fetch API to retrieve it and build the UI:

async function showProducts() {
  const response = await fetch('./products.json');
  const products = await response.json();
 
  const container = document.getElementById('products');
 
  products.forEach(product => {
    const card = document.createElement('div');
    card.textContent = `${product.name} - ${product.type}`;
    container.appendChild(card);
  });
}
 
showProducts();

The same approach works for dropdown selections, pricing cards, language lists, mock API results, or other JSON-driven interfaces. It keeps your content separate from your rendering code and makes updates easier.

You could also use inline JSON within the script if your data set is very small and remains constant. But an external JSON file is better if several pages or scripts require the same data.

If you want a live demo, you can paste these examples into CodePen, StackBlitz, or a small GitHub repository and serve the files through a local development server. Avoid opening the page only through file://, because browser security rules can interfere with fetching data from local files.

Conclusion

No particular method exists that would be considered the perfect way to parse JSON files in every case. For reading a JSON file served over HTTP, you can use fetch API, and FileReader for reading a JSON file selected by the user.

For module-based applications, data import becomes handy if the JSON data is bundled with the application. In Node.js, require() is great for basic CommonJS configuration parsing and fs.readFile() is better for asynchronous file reading.

For beginners, the easiest place to start is the fetch API in the browser and fs.readFile() in Node.js. Once you understand when parsing happens and whether your code is synchronous or asynchronous, working with the format becomes much more predictable.

Learn more
-

Related articles