50% OFF Residential Proxies for 9 months — use code IPR50 at checkout

Get The Deal
Back to blog

How to Read a JSON File in JavaScript: A Beginner-Friendly Guide

Learn how to effortlessly read JSON files using JavaScript with our step-by-step guide. Start coding with confidence.

Eugenijus Denisov

Last updated -
How to

Key Takeaways

  • A JSON file holds structured JSON data you can convert easily into a JavaScript object using - JSON.parse() or require().

  • In the browser, use the fetch API method and check the response object before parsing the file.

  • Always validate your JSON file, handle file path issues, and catch missing file errors to make your app stable.

Ready to get started?

Register now

When you’re gathering data from external sources, you may want to store it in a JSON file for clarity and readability. In some situations, you may need to read the JSON data you retrieved to make sure everything is the way it’s supposed to be.

Here, you will learn in what cases you may need to read JSON files in JavaScript, how to do it, and what common errors you could encounter.

What Is a JSON File?

A JSON file is an open standard format used for storing structured data. It contains key value pairs in a text format that both computers and humans can read and understand. For example, a sample JSON file might look like this:

{
  "name": "Alice",
  "age": 25,
  "city": "London"
}

This is a standard JSON format. Developers like to use it because it’s easy to turn into a JavaScript object and move between client and server. The JavaScript Object Notation (JSON) makes data exchange simple and easily understandable.

Why You Might Need to Read JSON Files in JavaScript

Reading a JavaScript file makes it easy to handle real-world tasks. Developers use it for many reasons, especially when working with dynamic or external data. Here’s a list of the most popular use cases:

  • Loading configuration settings. Projects often keep settings in JSON to control things like themes or server URLs.
  • Displaying content on websites. You might pull JSON data to fill product listings, user profiles, or blog articles. It keeps your HTML file clean and separates data from design.
  • Mocking API responses. During testing, developers use a local JSON file to act like real server data. This saves time and avoids extra server requests.
  • Internationalization. Translations for different languages can be stored as JSON data, then turned into a JS object to show the correct text on screen.
  • User input and forums. Save form responses in JSON format to keep things organized and flexible.
  • Game development. Store level designs, scores, or settings inside JSON, then load them into the game using a JavaScript function.

All in all, JavaScript gives you flexibility with how and where you manage your data while building tools, apps, or websites.

How to Read JSON Files in Node.js

In Node.js , you can read JSON using the built-in fs module. It gives you two main options: readFile for asynchronous reading, and readFileSync for synchronous reading.

Using fs.readFile (Asynchronous)

const fs = require('fs');

fs.readFile('./data.json', 'utf8', (err, data) => {
  if (err) {
    console.error('Failed to read file:', err);
    return;
  }
  const jsonData = JSON.parse(data);
  console.log(jsonData);
});

This method reads your JSON without blocking the app. It works great with larger projects or when performance is of utmost importance.

If you want to see the code in action, create a file called data.json in your project directory. You can fill it with information from the sample JSON file a few paragraphs above.

Using fs.readFileSync (Synchronous)

const fs = require('fs');

try {
  const rawData = fs.readFileSync('./data.json', 'utf8');
  const jsonData = JSON.parse(rawData);
  console.log(jsonData);
} catch (err) {
  console.error('Error reading JSON:', err);
}

This method blocks the app until the JSON file finishes loading. It’s easier to write but it’s not the best solution for apps where speed and performance is key.

Using require() for Static JSON Imports

When the JSON doesn’t change during runtime, you can load it directly with require:

const config = require('./config.json');
console.log(config);

Node automatically parses the JavaScript file into an object. This works well when loading fixed JSON data like app settings or presets.

This approach is simple and clean, but it only works with files available at load time, not for dynamic or external JSON file access.

How to Read JSON Files in the Browser

In a browser, you can use the fetch API to read a local JSON, as long as it’s served from an HTTP server and not opened directly from the file system:

async function loadJson() {
  try {
    const response = await fetch('data.json');
    
    // Check if request was successful
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    console.log(data);
    return data;
  } catch (err) {
    console.error('Error loading JSON:', err);
    throw err; // Re-throw so caller can handle it
  }
}

Here, the fetch API method returns an object that you can convert into a JavaScript object.

Follow these best practices for async handling with fetch API:

  • Use async/await.
  • Wrap fetch in try/catch.
  • Check response.ok before parsing.

If you’re interested, you may also want to learn how to parse JSON in JavaScript .

Common Errors and How to Avoid Them

While trying to read JSON in JavaScript, you may face some errors. Here are a few of the most common ones:

  • JSON parsing errors. Mistakes in JSON, such as missing commas can break parsing. Use a JSON validator to check your JSON file and fix any mistakes it outlines.
  • File path issues. Wrong paths in an HTML file or Node can lead to errors. To avoid that, double-check your path to the local JSON file.
  • Handling missing files. Always use try/catch or check for response.ok. This helps you catch missing or inaccessible files.

Conclusion

Reading JavaScript Object Notation is a useful skill to have. The ability to use Node, fetch API in a browser, and knowing how to turn a JSON string into a usable JavaScript object helps you manage settings, content, and external JSON data.

If you want to dig deeper, you can check out our article on how Python handles JSON in terms of parsing, reading, and writing.

Create Account

Author

Eugenijus Denisov

Senior Software Engineer

With over a decade of experience under his belt, Eugenijus has worked on a wide range of projects - from LMS (learning management system) to large-scale custom solutions for businesses and the medical sector. Proficient in PHP, Vue.js, Docker, MySQL, and TypeScript, Eugenijus is dedicated to writing high-quality code while fostering a collaborative team environment and optimizing work processes. Outside of work, you’ll find him running marathons and cycling challenging routes to recharge mentally and build self-confidence.

Learn More About Eugenijus Denisov
Share on

Related articles