What is edit-json-file?
The edit-json-file npm package allows you to easily read, edit, and write JSON files in a simple and straightforward manner. It provides a set of methods to manipulate JSON data without having to manually parse and stringify the JSON content.
What are edit-json-file's main functionalities?
Read JSON file
This feature allows you to read the contents of a JSON file. The `get` method retrieves the entire JSON object from the file.
const editJsonFile = require('edit-json-file');
let file = editJsonFile(`${__dirname}/data.json`);
console.log(file.get());
Set a value
This feature allows you to set a value in the JSON file. The `set` method takes a key and a value, and updates the JSON object. The `save` method writes the changes to the file.
const editJsonFile = require('edit-json-file');
let file = editJsonFile(`${__dirname}/data.json`);
file.set('name', 'John Doe');
file.save();
Unset a value
This feature allows you to remove a key-value pair from the JSON file. The `unset` method takes a key and removes it from the JSON object. The `save` method writes the changes to the file.
const editJsonFile = require('edit-json-file');
let file = editJsonFile(`${__dirname}/data.json`);
file.unset('name');
file.save();
Append to an array
This feature allows you to append a value to an array in the JSON file. The `append` method takes a key and a value, and adds the value to the array associated with the key. The `save` method writes the changes to the file.
const editJsonFile = require('edit-json-file');
let file = editJsonFile(`${__dirname}/data.json`);
file.append('items', 'newItem');
file.save();
Save the file
This feature allows you to save the changes made to the JSON file. The `save` method writes the updated JSON object back to the file.
const editJsonFile = require('edit-json-file');
let file = editJsonFile(`${__dirname}/data.json`);
file.set('name', 'John Doe');
file.save();
Other packages similar to edit-json-file
jsonfile
The jsonfile package provides similar functionality for reading and writing JSON files. It offers methods like `readFile` and `writeFile` for asynchronous operations, and `readFileSync` and `writeFileSync` for synchronous operations. Unlike edit-json-file, jsonfile does not provide methods for directly manipulating the JSON object.
node-json-db
The node-json-db package is a simple JSON-based database that allows you to store and retrieve data in JSON format. It provides methods for CRUD operations and supports nested objects. Compared to edit-json-file, node-json-db offers more advanced database-like features but may be overkill for simple JSON file manipulations.
edit-json-file
Edit a json file with ease.
:cloud: Installation
npm install --save edit-json-file
yarn add edit-json-file
:clipboard: Example
const editJsonFile = require("edit-json-file");
let file = editJsonFile(`${__dirname}/foo.json`);
file.set("planet", "Earth");
file.set("city\\.name", "anytown");
file.set("name.first", "Johnny");
file.set("name.last", "B.");
file.set("is_student", false);
file.append("classes", "fysics");
file.append("classes", { class: "Computer Science", where: "KULeuven" });
console.log(file.get());
file.pop("classes")
file.save();
file = editJsonFile(`${__dirname}/foo.json`, {
autosave: true
});
console.log(file.get("name.first"));
file.set("a.new.field.as.object", {
hello: "world"
});
console.log(file.toObject());
:question: Get Help
There are few ways to get help:
- Please post questions on Stack Overflow. You can open issues with questions, as long you add a link to your Stack Overflow question.
- For bug reports and feature requests, open issues. :bug:
- For direct and quick help, you can use Codementor. :rocket:
:memo: Documentation
JsonEditor(path, options)
Params
- String
path
: The path to the JSON file. - Object
options
: An object containing the following fields: stringify_width
(Number): The JSON stringify indent width (default: 2
).stringify_fn
(Function): A function used by JSON.stringify
.stringify_eol
(Boolean): Wheter to add the new line at the end of the file or not (default: false
)ignore_dots
(Boolean): Wheter to use the path including dots or have an object structure (default: false
)autosave
(Boolean): Save the file when setting some data in it.
Return
- JsonEditor The
JsonEditor
instance.
set(path, value, options)
Set a value in a specific path.
Params
- String
path
: The object path. - Anything
value
: The value. - Object
options
: The options for set-value (applied only when {ignore_dots} file option is false)
Return
- JsonEditor The
JsonEditor
instance.
get(path)
Get a value in a specific path.
Params
Return
- Value The object path value.
unset(path)
Remove a path from a JSON object.
Params
- String
path
: The object path.
Return
- JsonEditor The
JsonEditor
instance.
append(path, value)
Appends a value/object to a specific path.
If the path is empty it wil create a list.
Params
- String
path
: The object path. - Anything
value
: The value.
Return
- JsonEditor The
JsonEditor
instance.
pop(path)
Pop an array from a specific path.
Params
- String
path
: The object path.
Return
- JsonEditor The
JsonEditor
instance.
read(cb)
Read the JSON file.
Params
- Function
cb
: An optional callback function which will turn the function into an asynchronous one.
Return
- Object The object parsed as object or an empty object by default.
read(The, cb)
write
Write the JSON file.
Params
- String
The
: file content. - Function
cb
: An optional callback function which will turn the function into an asynchronous one.
Return
- JsonEditor The
JsonEditor
instance.
empty(cb)
Empty the JSON file content.
Params
- Function
cb
: The callback function.
toString()
Get the current data as string.
Return
- string The data as string.
save(cb)
Save the file back to disk.
Params
- Function
cb
: An optional callback function which will turn the function into an asynchronous one.
Return
- JsonEditor The
JsonEditor
instance.
toObject()
Return
editJsonFile(path, options)
Edit a json file.
Params
- String
path
: The path to the JSON file. - Object
options
: An object containing the following fields:
Return
- JsonEditor The
JsonEditor
instance.
:yum: How to contribute
Have an idea? Found a bug? See how to contribute.
:sparkling_heart: Support my projects
I open-source almost everything I can, and I try to reply to everyone needing help using these projects. Obviously,
this takes time. You can integrate and use these projects in your applications for free! You can even change the source code and redistribute (even resell it).
However, if you get some profit from this or just want to encourage me to continue creating stuff, there are few ways you can do it:
-
Starring and sharing the projects you like :rocket:
-
—I love books! I will remember you after years if you buy me one. :grin: :book:
-
—You can make one-time donations via PayPal. I'll probably buy a coffee tea. :tea:
-
—Set up a recurring monthly donation and you will get interesting news about what I'm doing (things that I don't share with everyone).
-
Bitcoin—You can send me bitcoins at this address (or scanning the code below): 1P9BRsmazNQcuyTxEqveUsnf5CERdq35V6
Thanks! :heart:
:dizzy: Where is this library used?
If you are using this library in one of your projects, add it in this list. :sparkles:
@genesislcap/build-kit
@acanto/laravel-scripts
@neutralinojs/neu
@dolittle/vanir-features
@nattyjs/cli
json-config-ts
@dolittle/vanir-cli
@airbnb/nimbus
soft-add-dependencies
@spazious/ts-config
@wonderland/cli-plugin-new
@spazious/eslint-config
@spazious/storybook-config
@formbird/core
check-dependency-version-consistency
@genesislcap/foundation-cli
menreiki-init
@olmokit/cli
@williarts/williarts-commons
admooh-cli
create-web-app-template
create-fw
create-nextjs-skeleton
create-itk-app
baelte-cli
deploi
@everything-registry/sub-chunk-1554
next-templates
lyo
live-stream-radio
mobcoder-node-express-typescript-generator
modern-project-generator
nipinit
monstro
jollofjs
noir-wp-cli
semcom
sheetbase-cli
typescript-react-native-starter
@kylehue/create-app
@frdl/legacy-and-deprecations-fallback
@sevta/cli
@johnlindquist/next-lesson
@wonderland/cli-plugin-serverless
copancs-microservice-teemplate
create-ts-jest
@bemedev/npm-publish
bhc-cli
blazar-cli
bucket-cli
@bitcoin-computer/node
bt-translate
@bronzw/create-discord-js-bot
@wonderland/new
@xploration-tech/xtouch
appium-reporter-plugin
aranha-commons
express-ts-app
doggoreportbot
infinicli
intelliter
fixed-minor-patch-package-json
fluxxo-generator
@dricup/dricup-cli
react-native-dom-expo
robinhood-yolo
simple-rtg
uspk-ui
typescript-fastify-starter
uiseeds
vcommit-cli
webify-generator
@malmo/cli
@mtmeyer/create-react-figma-plugin
@imklau/react-app
zoral-generator
@postlight/node-typescript-starter-kit
@teamhive/angular-npm-seed
@something.technology/core
chakra-12345
cmd-assistant
dukecbe
d-bot-script
create-any-app
create-express-ts-api
bloggify-tools
dricup-cli
@superjs/require-auto
@shoveller/copy-package
@orhanemree/create-template
@perlatsp/devild
@panfilo/express-template
typescript-vue-starter
typescript-express-starter
@mianfrigo/express-typescript-generator
@marvinkome/create-node-app
git-normalize
env-to-now-json
guser
my-chakra-ui
@dolittle/vanir-common
menreiki2
mf-webpack-plugin
@farazahmad759/dricup-crud-express
@j.u.p.iter/jupiter-scripts
crestron-angular-theme
@benits/teste-ui
cli-json-edit
boilerplate-templify-cli
ecochat-term
@grogqli/server
@genesislcap/genx2
typescript-nest-starter
typescript-koa-starter
torder-vue-cli
@allmywallets/specification
@jianghe/sand-cli
@kcom/package-tools
srf-deploy-qb
@elastosfoundation/trinity-cli
term-of-the-day
simple-webpack-starter
@spazious/config
@sapling/cli
@rajzik/lumos
@s-ui/changelog
neu-forge
malmo
modern-node-starter
node-rg
project-initializer
@dolittle/webpack
react-vscode-cli
react-sgh-scaffolding
returrn
@chakra-ui/codemod
forcemanager-cli
feeder-cli
easybackup
lerna-from-npm
@crestron/ch5-shell-utilities-cli
dricup
h4cksterbot
gyaon-cli
def-struct
iffe-cli
jad-node-ts-kit
@triptyk/nfw-cli
create-cubicus-frontend
base-express-app-starter
axereos-hopes
blip-lang
create-nuxt-typescript-component
copancs-microservice-template
build-swan-plugin
cucu-generator
create-cubicus-backend
create-express-template
create-express-typescript-application
@bemedev/publish-command
dex-cli
deyarn
deployqb
@colorfulcompany/create-cc-jlmf
fix-package-versions
express-generator-typescript-k8s
mongoose-auto-api.cli
next-nodecms
kanuki-cli
sisback
striplet
react-easy-boilerplate
ts-express-starter
typescript-react-starter
grafpad
iffe-commit
infinitumcli
@aburkov/scripts
mtm-cli
@acanto/workflow
@deboxsoft/plop-generator
new-express-app
jollof-cli
pandocuments
lazlodb
pkgmngrgui
@hyron/cli
@anyopsos/cli
@imklau/react-boilerplate
@geesmart/zxlib
@tinyhttp/cli
@fanxie/cli
@aquestsrl/create-app-cli
create-next-library
ss-clean-slate
:scroll: License
MIT © Ionică Bizău