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.
You are getting a JSON parse error because you are trying to parse the string
You should change your bash script to have:
Note the backquotes! Your string is a multiline string.
Here's a run (in one of my project directories):
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:ADDENDUM 2
You can even leave off the
console.log
if you use-p
:On linux system there is command jq which can parse the JSON files