Reading JSON in Node.js

Published on January 3, 2019

Reading from a JSON File

The standard built-in Javascript object JSON can be used to parse JSON strings.

const fs = require("fs");

// JSON file
let fileName = "data.json";

// the file is read synchronously in this example
// you can read it asynchronously also
let data = JSON.parse(fs.readFileSync(fileName));

// will output a Javascript object

JSON.parse method also accepts a second parameter, which is a function that can be executed to transform the data before being returned.

Reading JSON from a URL

In this case instead of reading the file from the fileystem, the JSON string is retrieved by sending a GET HTTP request to the url. After the response has been received, it can be read with JSON.parse.

const http = require('http');

let req = http.get("", function(res) {
	let data = '',

	res.on('data', function(stream) {
		data += stream;
	res.on('end', function() {
		json_data = JSON.parse(data);

		// will output a Javascript object

req.on('error', function(e) {

The http module is used to make a GET request. In case the url is a https one, use the https module.

In this Tutorial
    Loading Comments