Parse JSON in bash by piping it into Ruby:

echo '{"foo":"bar"}' | ruby -r json -e 'puts JSON.parse(["foo"]'
  • -r json is equivalent to calling require "json" in the code
  • -e 'some_ruby_code' will evaluate the Ruby code

Real world

You can use this to consume a JSON API. The following will fetch your current rate limit status from GitHub, parse the result and pass send it to statsd:

REMAINING_REQUESTS=$(curl -s | ruby -r json -e 'puts JSON.parse(["rate"]["remaining"]')
echo "github_rate_limit_remaining:${REMAINING_REQUESTS}|g" | nc -w 1 -u localhost 8125