How to access package.json fields


Here are the ways to get “version” from package.json:

package.json vars

There are npm environment variables for each package.json field:

$ npm run env | grep npm_package_

This means you can access version in a run-script:

// package.json
{
  "version": "1.2.3",
  "scripts": {
    "get-version": "echo $npm_package_version"
  }
}
$ npm run get-version

> @1.2.3 get-version path/to/package
> echo $npm_package_version

1.2.3

If you ever need to access npm environment variables outside the scope of run-scripts, you can parse the variables with bash:

$ npm run env | grep npm_package_version | cut -d '=' -f 2

jq

jq is a powerful tool for filtering JSON:

$ jq -r .version package.json

The -r option outputs the raw string (so it’s 1.2.3 instead of "1.2.3").

This means you can add a script like so:

// package.json
{
  "version": "1.2.3",
  "scripts": {
    "get-version": "jq -r .version package.json"
  }
}
$ npm run get-version

> @1.2.3 get-version path/to/package
> jq -r .version package.json

1.2.3

node

With Node.js, you can evaluate a script with the -e option:

$ node -e "console.log(require('./package.json').version)"

Furthermore, you can simplify the script by using the -p option to print the evaluation:

$ node -p "require('./package').version"

Thus, your script will look like so:

// package.json
{
  "version": "1.2.3",
  "scripts": {
    "get-version": "node -p \"require('./package').version\""
  }
}
$ npm run get-version

> @1.2.3 get-version path/to/package
> node -p "require('./package').version"

1.2.3

awk

You can always use awk to process text:

$ awk -F'"' '/"version": ".+"/{ print $4; exit; }' package.json

We’re matching package.json against the regex pattern /"version": ".+"/ and printing the 4th field of the first result.

The script will be as follows:

// package.json
{
  "version": "1.2.3",
  "scripts": {
    "get-version": "awk -F'\"' '/\"version\": \".+\"/{ print $4; exit; }' package.json"
  }
}
$ npm run get-version

> @1.2.3 get-version path/to/package
> awk -F'"' '/"version": ".+"/{ print $4; exit; }' package.json

1.2.3

Conclusion

Which approach worked for you? Tell us in the comments below!



If you enjoyed this post, please consider supporting this site!