Edit package.json from commandline

2019-03-08 04:03发布

问题:

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.

回答1:

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


回答2:

You can also use jq and sponge (moreutils package) like this :

jq '.foo="bar"' package.json | sponge package.json

With an environment variable :

jq --arg h "$HOMEPAGE" '.homepage=$h' package.json | sponge package.json


标签: json node.js npm