Read name property of package.json file with bash

2019-06-07 11:15发布

I have this:

str=`cat package.json`
prop="name"
my_val="$(node -e "console.log(JSON.parse(${str})[${prop}]);")"
echo "$my_val"

I want to read the name property of the package.json file. I think this is close, but I am getting a JSON.parse error:

SyntaxError: Unexpected token o in JSON at position 1
    at Object.parse (native)
    at [eval]:1:18
    at ContextifyScript.Script.runInThisContext (vm.js:25:33)
    at Object.runInThisContext (vm.js:97:38)

anyone know how to fix?

This works:

prop="name"
my_val="$(node -e "console.log(require('./package.json')['$prop'])")"
echo "json val: '$my_val'"

but I am wondering how to do it the first way.

2条回答
老娘就宠你
2楼-- · 2019-06-07 11:51

You are getting a JSON parse error because you are trying to parse the string

"[object Object]"

You should change your bash script to have:

node -e "console.log(JSON.parse(\`$str\`)['name'])"

Note the backquotes! Your string is a multiline string.

Here's a run (in one of my project directories):

$ str=`cat package.json`
$ prop="name"
$ myval="$(node -e "console.log(JSON.parse(\`$str\`)['$prop'])")"
$ echo $myval
plainscript

ADDENDUM

In response to the OP wishing to use require instead of echoing the contents of the file into a string, the solution can be as follows:

$ prop="name"
$ my_val="$(node -e "console.log(require('./package.json')['$prop'])")"
$ echo $my_val
plainscript

ADDENDUM 2

You can even leave off the console.log if you use -p:

$ prop="name"
$ my_val="$(node -pe "require('./package.json')['$prop']")"
$ echo $my_val
plainscript
查看更多
SAY GOODBYE
3楼-- · 2019-06-07 11:58

On linux system there is command jq which can parse the JSON files

jq -r ".name" package.json
查看更多
登录 后发表回答