Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

Monday, 14 April 2014

Parse JSON Content in Node JS

JSON.parse can be used to parse JSON Content.
The below example shows how to parse JSON content by reading it from a file.

Sample File with JSON Data (sample.js)
{
   "capital":"chennai",
   "location":"south",
   "stadium":{
      "cricket":"chepauk",
      "football":"mooremart"
   }
}

Node JS Code (jsonparser.js)
var fs = require('fs');

var content = fs.readFileSync('./sample.js').toString();

var jsoncontent = JSON.parse(content);
console.log(jsoncontent);

//Reading particular value
console.log("\nCapital is:" +jsoncontent.capital);
Running the Code
$ node jsonparser.js

{ capital: 'chennai',
  location: 'south',
  stadium: { cricket: 'chepauk', football: 'mooremart' } }

Capital is:chennai