Monday, June 24, 2024

How you can Import a JSON File in JavaScript/Node.js

Must read


JSON has turn out to be a preferred information format for its simplicity and compatibility with many programming languages, together with JavaScript. On this Byte, we’ll learn to simply import these recordsdata into your Node.js tasks.

Why Import JSON Information?

So why import JSON into your code? Effectively, JSON recordsdata are sometimes used to retailer information in a structured, easy-to-access method. They’re light-weight, human-readable, and may be simply imported into most programming languages.

In JavaScript, JSON recordsdata are notably helpful as a result of they are often parsed right into a native JavaScript object. This implies you may entry the info in a JSON file as if it had been a daily JavaScript object, making it a breeze to work with.

For example, in case you’re engaged on an internet software that should load configuration information, you would possibly select to retailer that information in a JSON file since you may simply edit the file your self. This lets you maintain not solely your config information straightforward to entry, however your code quite simple.

How you can Import JSON in Node.js

Utilizing the fs Module

Importing a JSON file in Node.js could be very straightforward to do since JSON is a local kind to JS. You should utilize the built-in fs (file system) module to learn the file, after which parse it right into a JavaScript object utilizing JSON.parse(). This is a easy instance:

const fs = require('fs');

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

On this code, fs.readFileSync('college students.json') reads the file college students.json synchronously, and returns the uncooked information (a string). JSON.parse(rawdata) then parses this string right into a JavaScript object, which we retailer within the college students variable.

Be aware: The readFileSync operate reads recordsdata synchronously, that means it blocks the remainder of your code from executing till it is executed. In the event you’re studying a big file, or if it is advisable learn a number of recordsdata, you would possibly need to use fs.readFile() as a substitute, which is asynchronous.

Utilizing CommonJS’s require

One other technique, and arguably an excellent easier one, is to make use of CommonJS’s require() operate, which is often used to load different Node recordsdata/packages.

One other good function of the require() technique is that it can be used to load JSON recordsdata, and it will return the file contents as a JSON object, so it handles the parsing for you.

This is do it, utilizing the same instance as above:

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

console.log(college students);

As you may see, it solely takes one line to load the JSON.

The one downsides is that it is perhaps slighly complicated to extra novice programmers since they may not bear in mind that require can be utilized on this approach and solely comprehend it as a solution to load code. Additionally, require caches no matter it hundreds, so if it is advisable reload a JSON file later in your program execution, it will nonetheless return the identical information, even when the file modified.

Potential Errors and Fixes

Whereas importing JSON recordsdata in Node.js is mostly easy, you continue to need to do correct error dealing with alongside the way in which. Let us take a look at a number of the most typical ones and repair them.

Error: JSON File Not Discovered

Most likely the obvious error you possibly can see is “Error: ENOENT: no such file or listing”. That is thrown when Node.js tries to learn a file that does not exist.

$ node app.js
    throw err;

Error: ENOENT: no such file or listing, open 'college students.json'

To repair this error, make certain the file you are attempting to learn truly exists, and that the trail to the file is right. If the file is in the identical listing as your JavaScript file and present working listing, you may simply use the filename. If it is in a special listing, you may want to incorporate 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 sometimes occurs when the construction of the JSON file does not adhere to the required syntax, which may be widespread for JSON recordsdata which are edited by hand. Keep in mind, JSON information is written as key/worth pairs, and keys have to be strings, enclosed in double quotes. That is not like the syntax for JS objects, which might trigger confusion, though the 2 are comparable.

This is a typical mistake:

    title: "John Doe", // Error: keys have to be in double quotes
    "age": 30,
    "metropolis": "New York"

The proper syntax can be:

    "title": "John Doe",
    "age": 30,
    "metropolis": "New York"

Hyperlink: Instruments like JSONLint may also help validate your JSON information and establish the place the errors lie.

Error: Import Assertion Not Suitable

One other widespread hiccup whereas importing JSON in Node.js is the incompatibility of the import assertion. Node.js makes use of CommonJS modules by default, so it does not natively assist ES6 import statements. In the event you attempt to use import to load your JSON file, you may doubtless encounter an error.

import information from './information.json'; // Error: Can not use import assertion outdoors a module

As a substitute, use the require() operate to import your JSON file:

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

This can load the JSON file and parse the JSON right into a JavaScript object like we confirmed earlier.


We have explored a couple of widespread methods to load JSON and errors you would possibly encounter whereas importing it in Node.js. Keep in mind, whereas require() is probably the most simple strategy, it may not at all times be the very best answer—particularly when coping with massive or altering recordsdata.

Supply hyperlink

More articles


Please enter your comment!
Please enter your name here

Latest article