a blog for those who code

Sunday, 12 June 2016

How To Parse JSON in Node.js

In this post we will be discussing about parsing JSON in Node.js. Collaborating JSON files with Node.js makes it simple to ensure that the information can be easily accessed by the users because choosing JSON files for storing data is a convenient option.

JSON or JavaScript Object Notation is a lightweight data format which can be either represented as a hash of properties and values or as a list of values.

What Exactly is Parsing JSON


Parsing means to separate into parts. When a server receive JSON as a data, it comes as a massive concatenation of characters (i.e. a huge string of data). Inside of that string there is an encoded tags as well as "name value" pairs. The parser takes this huge string and break it up into a data structures or say objects.

Ways of Parsing JSON in Node.js


There are number of ways in which you can parse JSON in Node.js and they are as follows.

1. Passing a string containing JSON data

If you have a string which contains JSON data then you can use  JSON.parse(). The JSON.parse() method parses a string as JSON, and optionally transfroming the value produced by parsing.

Examples are 

JSON.parse('{ "name1": "Coding", "name2": "Defined" }');
JSON.parse('null');


2. Parsing a file containing JSON data using file-system module

If you have a file, lets say (config.json) then you will have to do some file operations with fs module as shown below :

Asynchronous Version

var fs = require('fs');
var jsonData = '';
fs.readFile('./config.json', 'utf8', function (err, data) {
  if(err) throw err;
  jsonData = JSON.parse(data);
});

Synchronous Version

var fs = require('fs');
var jsonData = JSON.parse(fs.readFileSync('./config.json', 'utf8'));

3. Parsing a file containing JSON data using require module

The require() function in Node.js can read both .js and .json files. If a file ends with .js, the file is parsed and interpreted as a JavaScript file whereas if a file ends with .json, the file is parsed and interpreted as a JSON text file as shown below :

var config = require('./config.json');
console.log(config);
console.log('Value of Value1 is ' + config.value1);

4. Parsing a file using jsonfile module

If you have a large number of .json files then you can use jsonfile module as shown below.

var jf = require('jsonfile');
var jsonData = jf.readFileSync('./config.json');

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License