How to Import a JSON File in JavaScript/Node.js

Introduction

JSON has become a popular data format for its simplicity and compatibility with many programming languages, including JavaScript. In this Byte, we'll learn how to easily import these files into your Node.js projects.

Why Import JSON Files?

So why import JSON into your code? Well, JSON files are often used to store data in a structured, easy-to-access manner. They are lightweight, human-readable, and can be easily imported into most programming languages.

In JavaScript, JSON files are particularly useful because they can be parsed into a native JavaScript object. This means you can access the data in a JSON file as if it were a regular JavaScript object, making it a breeze to work with.

For instance, if you're working on a web application that needs to load configuration data, you might choose to store that data in a JSON file since you can easily edit the file yourself. This allows you to keep not only your config data easy to access, but your code very simple.

How to Import JSON in Node.js

Using the fs Module

Importing a JSON file in Node.js is very easy to do since JSON is a native type to JS. You can use the built-in fs (file system) module to read the file, and then parse it into a JavaScript object using JSON.parse(). Here's a simple example:

const fs = require('fs');

let rawdata = fs.readFileSync('students.json');
let students = JSON.parse(rawdata);
console.log(students);

In this code, fs.readFileSync('students.json') reads the file students.json synchronously, and returns the raw data (a string). JSON.parse(rawdata) then parses this string into a JavaScript object, which we store in the students variable.

Note: The readFileSync function reads files synchronously, meaning it blocks the rest of your code from executing until it's done. If you're reading a large file, or if you need to read multiple files, you might want to use fs.readFile() instead, which is asynchronous.

Using CommonJS's require

Another method, and arguably an even simpler one, is to use CommonJS's require() function, which is typically used to load other Node files/packages.

Another nice feature of the require() method is that it can also be used to load JSON files, and it'll return the file contents as a JSON object, so it handles the parsing for you.

Here's how to do it, using a similar example as above:

let rawdata = require('students.json');

console.log(students);

As you can see, it only takes one line to load the JSON.

The only downsides is that it might be slighly confusing to more novice programmers since they might not be aware that require can be used in this way and only know it as a way to load code. Also, require caches whatever it loads, so if you need to reload a JSON file later in your program execution, it'll still return the same data, even if the file changed.

Potential Errors and Fixes

While importing JSON files in Node.js is generally simple, you still have to do proper error handling along the way. Let's look at some of the most common ones and how to fix them.

Error: JSON File Not Found

Probably the most obvious error you could see is "Error: ENOENT: no such file or directory". This is thrown when Node.js tries to read a file that doesn't exist.

$ node app.js
fs.js:114
    throw err;
    ^

Error: ENOENT: no such file or directory, open 'students.json'
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

To fix this error, make sure the file you're trying to read actually exists, and that the path to the file is correct. If the file is in the same directory as your JavaScript file and current working directory, you can just use the filename. If it's in a different directory, you'll need to include the relative or absolute path to the file, like so:

let rawdata = fs.readFileSync('./path/to/your/file.json');

Error: Invalid JSON Format

This error typically happens when the structure of the JSON file doesn't adhere to the required syntax, which can be common for JSON files that are edited by hand. Remember, JSON data is written as key/value pairs, and keys must be strings, enclosed in double quotes. This is unlike the syntax for JS objects, which can cause confusion, even though the two are similar.

Here's a common mistake:

{
    name: "John Doe", // Error: keys must be in double quotes
    "age": 30,
    "city": "New York"
}

The correct syntax would be:

{
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

Link: Tools like JSONLint can help validate your JSON data and identify where the errors lie.

Error: Import Statement Not Compatible

Another common hiccup while importing JSON in Node.js is the incompatibility of the import statement. Node.js uses CommonJS modules by default, so it doesn't natively support ES6 import statements. If you try to use import to load your JSON file, you'll likely encounter an error.

import data from './data.json'; // Error: Cannot use import statement outside a module

Instead, use the require() function to import your JSON file:

const data = require('./data.json');

This will load the JSON file and parse the JSON into a JavaScript object like we showed earlier.

Conclusion

We've explored a few common ways to load JSON and errors you might encounter while importing it in Node.js. Remember, while require() is the most straightforward approach, it might not always be the best solution—especially when dealing with large or changing files.

Last Updated: September 18th, 2023
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms