At first I tried googling about it, I found a solution, which shows example with file system support of nodejs(fs module). But, I don’t really see any meaning of that at all, as we can simply do the same thing by:

var jsonObj = require("./path/to/myjsonfile.json");

Here, NodeJS automatically read the file, parse the content to a JSON object and assigns that to the left hand side variable. It’s as simple as that!

Add New Element To Existing JSON Object:


Say, you have an existing json object, which you want to modify to add new key/value pair(s). You can do that using either of the two ways as below:

var myJson = {'key':'value'};
//new element
myJson.key2 = 'value2';
//or
myJson[key3] = 'value3';

Delete An Element From A JSON Object:


Well, to delete an element from a JSON object, it can be done by using the ‘delete’ keyword. An example is given below:

var myJson = {'key':'value'};
delete myJson['key'];
Iterate Over A JSON Object:


Sometimes you will might need to traverse through each elements of the JSON object. This can be done in a for loop easily as like below:

var myJson = {'key':'value', 'key2':'value2'};
for(var myKey in myJson) {
   console.log("key:"+myKey+", value:"+myJson[myKey]);
}


However, the above code could give you error in case the value itself is a JSON object. So, you will might want to check whether the value is itself json or not and handle it thereby.

Check Key Existence:


If at some point we need to check whether a json object have a specific key, we can check that with below approach:

var myJson = {'key':'value', 'key2':'value2'};
if(myJson.hasOwnProperty('key2')){
     //do something if the key exist
}

Pretty Print JSON Object:


In debugging, we alway like to print data to console to verify if its OK. If you are trying to see if a large JSON has something you are expecting, then its very hard to locate if its printed in flat structure. In Such cases, what you need is pretty printing the JSON object. Here is the javascript code snippet that will do the trick:

JSON.stringify(myObj, null, 2);


Same applies if you are trying to write the json object in a file with pretty printed format.

来源:http://codesamplez.com/programming/using-json-in-node-js-javascript