rjq: Use Ruby to query JSON on the CLI

In my day-to-day work, I spend a lot of time working with JSON, and and one of my favourite tools for working with JSON is jq. Jq is an excellent tool for working with JSON on the command line … however, I can never remember what arcane syntax I need to use to accomplish the simplest of queries. So, as any mediocre programmer, I built my own jq in my favourite language, Ruby.

How it works

rjq is a very simple program, in fact in it's original release, it's just 3 lines:

#! /usr/bin/env ruby
require 'json'
puts eval(%{JSON.parse(STDIN.read)#{ARGV[0]}})

If you're familiar with Ruby, this should all make sense … and you've probably noticed that eval call, yes, the user input to rjq is just superglued on to the back of the instantiated Hash or Array from the JSON.

Examples

We'll use the GOV UK bank holidays API as an example data source.

Firstly, we'll just get the top level keys in the dataset:

~/ curl -s https://www.gov.uk/bank-holidays.json | rjq ".keys"
england-and-wales
scotland
northern-ireland

Next, we'll use a simple Ruby enumerable map to return a new formatted list of bank holidays in England and Wales:

~/ curl -s https://www.gov.uk/bank-holidays.json | rjq "['england-and-wales']['events'].map{|e| %(#{e['title']} #{e['date']} #{'πŸŽ‰' if e['bunting']} ) }"
New Year’s Day 2016-01-01 πŸŽ‰
Good Friday 2016-03-25
Easter Monday 2016-03-28 πŸŽ‰
Early May bank holiday 2016-05-02 πŸŽ‰
Spring bank holiday 2016-05-30 πŸŽ‰
Summer bank holiday 2016-08-29 πŸŽ‰
Boxing Day 2016-12-26 πŸŽ‰
Christmas Day 2016-12-27 πŸŽ‰
New Year’s Day 2017-01-02 πŸŽ‰
Good Friday 2017-04-14
Easter Monday 2017-04-17 πŸŽ‰
Early May bank holiday 2017-05-01 πŸŽ‰
Spring bank holiday 2017-05-29 πŸŽ‰

Should I use this?

As you can see, it's just simple Ruby, however, there is that eval command in there, which has the potential to introduce security concerns. You should always check the JSON datasource is trusted before operating on it.

GitHub: phil/rjq

https://github.com/phil/rjq

About the Author

Phil Balchin is a full-time software developer at Zendesk, previously at Heroku/Salesforce, and Kyan, as well as a part-time photographer living in Guildford, Surrey, UK.

facebook.com/phil.balchin | instagram.com/maniacalrobot | last.fm/users/maniacalrobot | picfair.com/maniacalrobot | maniacalrobot.tumblr.com | twitter.com/maniacalrobot
© 2011–2024 Philip Balchin | About | sitemap | Colophon | RSS | Ο€