logo
post image

Reading JSON in Node.js

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
console.log(data);

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("http://site.com/data.json", function(res) {
	let data = '',
		json_data;

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

		// will output a Javascript object
		console.log(json_data);
	});
});

req.on('error', function(e) {
    console.log(e.message);
});

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