Skip to content

Instantly share code, notes, and snippets.

@GuillermoPena
Created May 28, 2014 09:55
Show Gist options
  • Save GuillermoPena/4ca44dc20757f4008586 to your computer and use it in GitHub Desktop.
Save GuillermoPena/4ca44dc20757f4008586 to your computer and use it in GitHub Desktop.
NodeJS - JSON : Objects and files
//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