jsonfile

Easily read/write JSON files.

Node.js - jsonfile

Easily read/write JSON files.

Writing JSON.stringify() and then fs.writeFile() and JSON.parse() with fs.readFile() enclosed in try/catch blocks became annoying.

npm install jsonfile --save
var jf = require('jsonfile')
var util = require('util')
 
var file = '/tmp/data.json'
jf.readFile(file, function(errobj) {
  console.log(util.inspect(obj))
})
var jf = require('jsonfile')
var util = require('util')
 
var file = '/tmp/data.json'
 
console.log(util.inspect(jf.readFileSync(file)))

options: throws. Set to false if you don't ever want this method to throw on invalid JSON. Will return null instead. Defaults to true. Others passed directly to fs.readFileSync.

var jf = require('jsonfile')
 
var file = '/tmp/data.json'
var obj = {name: 'JP'}
 
jf.writeFile(file, obj, function(err) {
  console.log(err)
})
var jf = require('jsonfile')
 
var file = '/tmp/data.json'
var obj = {name: 'JP'}
 
jf.writeFileSync(file, obj)

Number of spaces to indent JSON files.

default: 2

var jf = require('jsonfile')
 
jf.spaces = 4;
 
var file = '/tmp/data.json'
var obj = {name: 'JP'}
 
jf.writeFile(file, obj, function(err) { //json file has four space indenting now
  console.log(err)
})

If you contribute to this library, please don't change the version numbers in your pull request.

(You can add your name, or I'll add it if you forget)

(MIT License)

Copyright 2012-2014, JP Richardson jprichardson@gmail.com