使用方式
[VAR]=readJson [filename] [key] || exit [code]
其中:
[VAR]
is a bash variable where you want to assign the result string[filename]
is the source JSON file[key]
is the identifier[code]
is the non-zero error code returned if the value is not found
function readJson {
UNAMESTR=`uname`
if [[ "$UNAMESTR" == 'Linux' ]]; then
SED_EXTENDED='-r'
elif [[ "$UNAMESTR" == 'Darwin' ]]; then
SED_EXTENDED='-E'
fi;
VALUE=`grep -m 1 "\"${2}\"" ${1} | sed ${SED_EXTENDED} 's/^ *//;s/.*: *"//;s/",?//'`
if [ ! "$VALUE" ]; then
echo "Error: Cannot find \"${2}\" in ${1}" >&2;
exit 1;
else
echo $VALUE ;
fi;
}