How to load a JSON file in NodeJS

This is another short, but useful tutorial for beginners. In this post I’m going to show how to load the following JSON dataset with NodeJS:

dataset.json

[{"id":1,"first_name":"Philip"},
{"id":2,"first_name":"Dorothy"},
{"id":3,"first_name":"Kathleen"},
{"id":4,"first_name":"Arthur"},
{"id":5,"first_name":"Robin"},
{"id":6,"first_name":"Douglas"},
{"id":7,"first_name":"Theresa"}]

We don’t have to create an entire project with express to read this file, a simple js file will do.

node-json.js

 var fs = require("fs");
 
 var jsonAsString = fs.readFileSync("dataset.json");
 var jsonArray = JSON.parse(jsonAsString);
 
jsonArray.forEach(function(row){
  console.log("Id:", row.id);
  console.log("Email:", row.first_name);
});

To load the file we have to provide url to the function readFileSync from fs (File System), it’ll return the content as an string. Before we can use it we just have to convert it to JSON with JSON.parse.

You can execute your code via the command: node node-json.js. If it works it’ll print all the json data on your terminal.

Recommended for you

Tutorial: Creating a Realtime Notification System in Angular and Nodejs Notification System Demo In this post I'm going to show you how to create a simple realtime notification system using Angular, Nodejs and Socket.io. It will offer a page where we will be able to create notifications and broadcast it to all the online users. I'll be making it as basic as possible...
How to Load a JSON file in Angular2 Angular2 makes it very easy for us to load data from JSON files, we can do it by simply making a http request. Now let's see how we can do that. To be able to make Http requests we first have to import the HttpModule on the app.module.ts, once you've done that your code should look like this: ...
How to Execute a .jar File with Node.js Child Processes You probably have already come across situations where your application had to execute other applications or native commands from the OS. Node.js can easily do that by spawning child processes. To show you how to do that I'm going to give you an example of how to execute a .jar file with node. Fi...
Nodejs Totorial: Creating and Using Events Nodejs makes it very easy for us to use events, and we're not limited to a collection of predefined events, it has a built-in module that allows us create and emit our own events. Let me show you how easy it is to use this module, first we have require the events module and create the event emitt...

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>