GithubHelp home page GithubHelp logo

edit-json-file's Introduction

edit-json-file

Support me on Patreon Buy me a book PayPal Ask me anything Version Downloads Get help on Codementor

Buy Me A Coffee

Edit a json file with ease.

โ˜๏ธ Installation

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

# Using yarn
yarn add edit-json-file

๐Ÿ“‹ Example

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] } } }

โ“ Get Help

There are few ways to get help:

  1. Please post questions on Stack Overflow. 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. ๐Ÿ›
  3. For direct and quick help, you can use Codementor. ๐Ÿš€

๐Ÿ“ 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.

๐Ÿ˜‹ How to contribute

Have an idea? Found a bug? See how to contribute.

๐Ÿ’– 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 ๐Ÿš€

  • Buy me a bookโ€”I love books! I will remember you after years if you buy me one. ๐Ÿ˜ ๐Ÿ“–

  • PayPalโ€”You can make one-time donations via PayPal. I'll probably buy a coffee tea. ๐Ÿต

  • Support me on 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

Thanks! โค๏ธ

๐Ÿ’ซ Where is this library used?

If you are using this library in one of your projects, add it in this list. โœจ

  • @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

๐Ÿ“œ License

MIT ยฉ Ionicฤƒ Bizฤƒu

edit-json-file's People

Contributors

acconrad avatar calvinrodo avatar dependabot[bot] avatar flucivja avatar ionicabizau avatar michielgeyskens avatar natanavra avatar srbrahma avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

edit-json-file's Issues

Will multiple edit calls to same file from different hosts fail ?

Hi
I am exploring your library. There is a single file that can be accessed by multiple users at a time.

let file = editJsonFile("path");
file.set("KEY", "VALUE");

How will this library act in this scenario? Is there any provision of lock & wait in this library ?

Hi, how to change data inside array?

I.e. we have some json like

{
  "boards": [
    {
      "id": 1,
      "status": "active",
      "date": ""
     }
   ]
}

So how can I select first element in array boards and set the date there?

Can I edit The Item In an array?

example

{
    "data": [
        {
            "id": "1",
            "message": "hello world"
        },
        {
            "id": "2",
            "message": "hello worl3"
        }
    ]
}

how can I get the path of the id2

file.append('data[0].status', true)

But it is not work.

Can't use relative path

Can't use a relative path(ex. ../tmp.json or ./config.json). Please give me an example if you can

P.S currently using

const {resolve} = require('path')
resolve('../../bb/tmp.txt')

To convert relative path to absolute

Remove values

Edit implies both add and remove. Currently you can only add to a JSON file, but not remove from it. I'd like to be able to add that functionality. The creators of set-value created an equivalent unset-value which should make this change trivial.

Parent and Key Values are not updating

During parallel execution, When I try to set values in a JSON of 25 test cases at a same time, Set Values are not updating. This is working fine when I update the JSON one by one.

Support JSON with Comments

tsconfig.json files use a format called JSON with comments...

/*
In a world
Where comments are supported.
YAML doesn't exist.
*/
{
  // tsconfig.json reference: typescriptlang.org/v2/en/tsconfig
  // "files": ["src/schedule.ts"],
  // "include": ["src/*", "test/schedule_test.ts"],
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

push to Array feature

how about

let blabla = []
file.set("blabla", blabla)

setInterval(() => {
  blabla.push("ebebe")
  file.set("blabla", blabla)
}, 1000)  

to

let blabla = []
file.set("blabla", blabla)

setInterval(() => {
  file.push("blabla", "ebebe")
}, 1000)  

for not to rewrite
O(n) -> O(1)

How to set keys with periods in them.

I'm trying to write a little tool to add keys to some json files.

The files have keys in the format "foo.bar" is there any way to add these keys using this tool? I'm not able to figure it out.

Duplicate keys lost

Values for duplicate object keys as seen in simulated package.json comments are lost when editing a file.

Before editing package.json:

{
  "dependencies": {
    "//": "comment about foo",
    "foo": "^1.2.3",
    "//": "comment about bar",
    "bar": "^4.5.6",
    "//": "comment about baz",
    "baz": "^7.8.9",
  }
}

After some arbitrary edit to package.json:

{
  "dependencies": {
    "//": "comment about baz",
    "foo": "^1.2.3",
    "bar": "^4.5.6",
    "baz": "^7.8.9",
  }
}

While I don't expect to be able to edit the duplicate keys as there's no way to refer to them individually, I do need to be able to edit other data in the file without losing the comments.

Note that this is different from #40 which is referring to actual comments, not the simulated comments involved here.

This bug causes me a problem in my tool in bmish/check-dependency-version-consistency#536.

Don't allow JSON5 [tsconfig.json file]

Hey, nice package.

However, I can't read nor add new items to a .json with comments, like a tsconfig.json file. When reading, it will read an empty object, and when adding an item, it will clean the file before.

I know comments aren't part of the current JSON standard (but JSON 5), but would be a nice and useful addition to the package.

A tsconfig.json example
{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
    // "noUncheckedIndexedAccess": true,      /* Include 'undefined' in index signature results */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true,  /* Disallow inconsistently-cased references to the same file. */
    "resolveJsonModule": true
  }
}

set() function asychronous or synchronous

I wanted to know if tne set() funtion is synchronous or asynchronous, and if it is asynchronous, can multiple requests at the same time fail when writing to a document, in this case, will autosave fix this ?

Use number as key

I'd like to use an ID as key.
messageFile.set("messages." + message.id + ".text", message.text);
But I'm getting a lot of null rows generated
image
The reason is that the tool thinks that I want to generate an array and fills up the empty rows with null.

json Array

Want to use with JSON 2D array. Can you please add a little bit of info about 2D array?

Typo in README/DOCUMENTATION

Hello, I found a typo in the README/DOCUMENTATION files. Specifically, there are two appends and I think the second append should actually be pop. Also, I wasn't sure what the best way to edit the README is since the comment at the top mentions editing the blah field in package.json which I don't see, so I created this issue.

Error: Unable to resolve module fs

Error: Unable to resolve module fs
setValue = require("set-value"),

rJson = require("r-json"),
fs = require("fs"),
^
iterateObject = require("iterate-object"),
os = require('os');
Simulator Screen Shot - iPhone 12 - 2022-01-20 at 19 30 41

High Severity Vulnerability: Prototype Pollution in set-value

@IonicaBizau I can see this issue is already fixed in your repository but we just need a new release to be able to use it. :)

# npm audit report

set-value  <4.0.1
Severity: high
Prototype Pollution in set-value - https://github.com/advisories/GHSA-4jqc-8m5r-9rpr
No fix available
node_modules/set-value
  edit-json-file  *
  Depends on vulnerable versions of set-value
  node_modules/edit-json-file

2 high severity vulnerabilities

Some issues need review, and may require choosing
a different dependency.

Fix:
update dependency set-value to version 4.0.1

Already done:

"set-value": "^4.0.1",

As of this commit:
0a522ad

Many thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.