Update: Feb 2017. If you have node, this one liner makes it much simpler.

PKG_VERSION=`node -p "require('./package.json').version"`  

Original Post:

Function Definition

Drop the following function into your bash script. It works on Linux and OSX. You’d likely use this if you don’t have node available.

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

Usage

[VAR]=readJson [filename] [key] || exit [code] where:

  • [VAR] is a bash variable where you want to assign the result string
  • [filename] is the source JSON file
  • [key] is the identifier
  • and [code] is the non-zero error code returned if the value is not found

Don’t want to quit when there’s no identifier? Then remove the || exit command suffix, though you’ll still get a message in stderr.

Example

Give this source file package.json:

{
  "name": "sample-project",
  "description": "A great project"
}

You could make a simple bash script to read those values:

#!/bin/bash

# paste the readJson function here or source it from a separate file

NAME=`readJson package.json name` || exit 1;  
# $NAME is "sample-project"

DESC=`readJson package.json description` || exit 2;  
# $DESC is "A great project"

Error Handling

If a value is not found, the script will exit and report to stderr. It’s your choice to customize the exit codes per value read in, though they can all be code 1 for example.

Caveats

  1. The function doesn’t account for multiple values in the JSON definition, for example, many identifiers of the same name in a collection. It only reads the first matching line as determined by the -m 1 argument.
  2. The source JSON file doesn’t have to be valid JSON… at least this function doesn’t check for validity. If the JSON is invalid, you might get unexpected results.
  3. An escaped quote within a JSON value may produce a false positive match.