Skip to content

Read from and write to a JSON file, minimizing diffs and preserving formatting.

License

Notifications You must be signed in to change notification settings

ljharb/json-file-plus

Repository files navigation

json-file-plus Version Badge

github actions coverage dependency status dev dependency status License Downloads

npm badge

A module to read from and write to JSON files, without losing formatting, to minimize diffs.

Example

const jsonFile = require('json-file-plus');
const path = require('path');
const filename = path.join(process.cwd(), 'package.json');

jsonFile(filename).then((file) => {
	file.data; // Direct access to the data from the file
	file.format; // extracted formatting data. change at will.

	file.get('version'); // get top-level keys. returns a Promise
	file.get(); // get entire data. returns a Promise

	/* pass any plain object into "set" to merge in a deep copy */
	/* please note: references will be broken. */
	/* if a non-plain object is passed, will throw a TypeError. */
	file.set({
		foo: 'bar',
		bar: {
			baz: true,
		},
	});

	file.remove('description'); // remove a specific key-value pair. returns a Promise

	/* change the filename if desired */
	file.filename = path.join(process.cwd(), 'new-package.json');

	/* Save the file, preserving formatting. returns a Promise. */
	file.save().then(function () {
		console.log('success!');
	}).catch(function (err) {
		console.log('error!', err);
	});
});

Tests

Simply run npm test in the repo

About

Read from and write to a JSON file, minimizing diffs and preserving formatting.

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •