Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/IonicaBizau/edit-json-file

Edit a json file with ease.
https://github.com/IonicaBizau/edit-json-file

hacktoberfest

Last synced: about 2 months ago
JSON representation

Edit a json file with ease.

Awesome Lists containing this project

README

        

# edit-json-file

[![Support me on Patreon][badge_patreon]][patreon] [![Buy me a book][badge_amazon]][amazon] [![PayPal][badge_paypal_donate]][paypal-donations] [![Ask me anything](https://img.shields.io/badge/ask%20me-anything-1abc9c.svg)](https://github.com/IonicaBizau/ama) [![Version](https://img.shields.io/npm/v/edit-json-file.svg)](https://www.npmjs.com/package/edit-json-file) [![Downloads](https://img.shields.io/npm/dt/edit-json-file.svg)](https://www.npmjs.com/package/edit-json-file) [![Get help on Codementor](https://cdn.codementor.io/badges/get_help_github.svg)](https://www.codementor.io/johnnyb?utm_source=github&utm_medium=button&utm_term=johnnyb&utm_campaign=github)

Buy Me A Coffee

> Edit a json file with ease.

## :cloud: Installation

```sh
# Using npm
npm install --save edit-json-file

# Using yarn
yarn add edit-json-file
```

## :clipboard: Example

```js
const editJsonFile = require("edit-json-file");

// If the file doesn't exist, the content will be an empty object by default.
let file = editJsonFile(`${__dirname}/foo.json`);

// Set a couple of fields
file.set("planet", "Earth");
file.set("city\\.name", "anytown");
file.set("name.first", "Johnny");
file.set("name.last", "B.");
file.set("is_student", false);
//Create or append to an array
file.append("classes", "fysics");
//You can even append objects
file.append("classes", { class: "Computer Science", where: "KULeuven" });

// Output the content
console.log(file.get());
// { planet: 'Earth',
// city.name: 'anytown',
// name: { first: 'Johnny', last: 'B.' },
// is_student: false,
// classes: [
// 'fysics',
// {
// 'class': 'Computer Science',
// 'where': 'KULeuven'
// }
// ]
// }

//if you want to remove the last element from an array use pop
file.pop("classes")

// Save the data to the disk
file.save();

// Reload it from the disk
file = editJsonFile(`${__dirname}/foo.json`, {
autosave: true
});

// Get one field
console.log(file.get("name.first"));
// => Johnny

// This will save it to disk
file.set("a.new.field.as.object", {
hello: "world"
});

// Output the whole thing
console.log(file.toObject());
// { planet: 'Earth',
// name: { first: 'Johnny', last: 'B.' },
// is_student: false,
// a: { new: { field: [Object] } } }
```

## :question: Get Help

There are few ways to get help:

1. Please [post questions on Stack Overflow](https://stackoverflow.com/questions/ask). You can open issues with questions, as long you add a link to your Stack Overflow question.
2. For bug reports and feature requests, open issues. :bug:
3. For direct and quick help, you can [use Codementor](https://www.codementor.io/johnnyb). :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

- **String** `path`:

#### 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
- **Object** The data object.

### `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][contributing].

## :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:
- [![Buy me a book][badge_amazon]][amazon]—I love books! I will remember you after years if you buy me one. :grin: :book:
- [![PayPal][badge_paypal]][paypal-donations]—You can make one-time donations via PayPal. I'll probably buy a ~~coffee~~ tea. :tea:
- [![Support me on Patreon][badge_patreon]][patreon]—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`

![](https://i.imgur.com/z6OQI95.png)

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][license] © [Ionică Bizău][website]

[license]: /LICENSE
[website]: https://ionicabizau.net
[contributing]: /CONTRIBUTING.md
[docs]: /DOCUMENTATION.md
[badge_patreon]: https://ionicabizau.github.io/badges/patreon.svg
[badge_amazon]: https://ionicabizau.github.io/badges/amazon.svg
[badge_paypal]: https://ionicabizau.github.io/badges/paypal.svg
[badge_paypal_donate]: https://ionicabizau.github.io/badges/paypal_donate.svg
[patreon]: https://www.patreon.com/ionicabizau
[amazon]: http://amzn.eu/hRo9sIZ
[paypal-donations]: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=RVXDDLKKLQRJW