Created
May 28, 2014 09:55
-
-
Save GuillermoPena/4ca44dc20757f4008586 to your computer and use it in GitHub Desktop.
NodeJS - JSON : Objects and files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Read json object from json file. | |
//Write json object to json file | |
var fs = require('fs') | |
var util = require('util') | |
// __dirname is folder where script is running | |
// NOTE: Use always " in json file content | |
var cfgFile = __dirname + "/anything.json" | |
// Reading JSON file to object | |
var cfgFileContent = fs.readFileSync(cfgFile) | |
var config = JSON.parse(cfgFileContent) | |
console.log(util.inspect(config)) | |
// Writing object to a JSON file | |
var file = __dirname + '/object.json' | |
var object = { | |
"cities": [ "Madrid", "Barcelona", "Valencia"], | |
"person": { "name": "Guillermo", | |
"surname": "Peña", | |
"age": 36 | |
}, | |
"anything": "Hello!" | |
} | |
fs.writeFileSync(file, JSON.stringify(object)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment