Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit package.json from command line

Tags:

json

node.js

npm

I'm trying to add or edit a variable in my package.json from a shell script. So if i have a package.json like this:

{   "name": "my-project",   "description": "Project by @DerZyklop",   "version": "0.0.0",   ... 

I want a command like

npm config set foo bar 

that adds a new field like

{   "name": "my-project",   "description": "Project by @DerZyklop",   "foo": "bar",   "version": "0.0.0",   ... 

...but unfortunately npm config set just edits the ~/.npmrc and not my package.json.

like image 324
DerZyklop Avatar asked Aug 15 '14 15:08

DerZyklop


People also ask

Can I modify package json file?

you can just open it with nano and edit it manually...

Can I manually edit package-lock json?

json file is present, npm install will install the exact versions specified. The package-lock. json is not meant to be human-readable, and it's not meant to be edited manually.

Does npm install modify package json?

npm ci will install packages based on package-lock. json file and if the file does not exist or does not match the packages specified in the package. json it will throw an error and fail.


2 Answers

The package.json is just a json file, so you could use the tool json. To install it use:

npm install -g json 

Then you can edit a file in-place. More information here.

Example

$ cat package.json {   "name": "my-project",   "description": "Project by @DerZyklop",   "version": "0.0.0" }  $ json -I -f package.json -e "this.foo=\"bar\"" json: updated "package.json" in-place  $ cat package.json {   "name": "my-project",   "description": "Project by @DerZyklop",   "version": "0.0.0",   "foo": "bar" } 
like image 122
enrico.bacis Avatar answered Sep 19 '22 03:09

enrico.bacis


If you don't want to install sponge or json, you can also do

echo "`jq '.foo="bar"' package.json`" > package.json 
like image 45
Amy Guo Avatar answered Sep 21 '22 03:09

Amy Guo