By using
require()
function the developer can load JSON file into the Node.js . Now lets take two files such as config.js and config.json.
config.js
[html]
module.exports = {
server: "localhost",
port: 1234,
timeout: 10
};
[/html]
config.json
[html]
{
"server": "localhost",
"port": 1234,
"timeout": 10
}
[/html]
Now above two will be read out by using require() as follows.
[html]
// When loading a configuration file, we have the choice to load either .js file,
// which will be interpreted as a JavaScript module file, with the "exports" being
// returned from the require; or, we can load a .json file, which will be parsed as
// JavaScript Object Notation (JSON) with the result being returned from the require.
// Load configuration as JSON.
console.log( "JSON File:" );
console.log( require( "./config.json" ) );
// Load configuration as module.
console.log( "MODULE File:" );
console.log( require( "./config.js" ) );
[/html]
Output: Now compile the code result will be as follows.
ben$ node explicit-ext.js
JSON File:
{ server: 'localhost', port: 1234, timeout: 10 }
MODULE File:
{ server: 'localhost', port: 1234, timeout: 10 }
By using the built-in global a string will be converted into JSON Object as follows.
[html]
var jsonString = "{\"key\":\"value\"}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.key);
[/html]
By using the stringify method a JSON Object will be converted into string as follows.
[html]
var jsonObj = {'key':'value'};
console.log(JSON.stringify(jsonObj));
[/html]
Read JSON From File System In NodeJS
The following is the code.
[html]var jsonObj = require("./path/to/myjsonfile.json");[/html]
Here, NodeJS consequently read the document, parse the substance to a JSON protest and gives that to left side of the variable.
Add New Element To JSON Object
The following is the code to add the new element to the existing JSON object.
[html]
var myJson = {'key':'value'};
//new element
myJson.key2 = 'value2';
//or
myJson[key3] = 'value3';
[/html]
Delete An Element From A JSON Object
The following is the code to delete the element from the JSON object.
[html]
var myJson = {'key':'value'};
delete myJson['key'];
[/html]