jq for JSON

By  on  

I old enough to remember when we thought XML was going to change the programming world...then JSON saved us from that hell. Parsing and querying JSON data is fundamental task we've all coded for, but sometimes I just want to get some data locally with minimal fuss. I just learned of a really awesome library to do so: jq. Let's have a look at some cool things we can do with jq!

Start by installing jq via a utility like Homebrew:

brew install jq

With Homebrew installed and a local actors.json file, let's go to work on pulling some data!

// Using this JSON file:
// https://raw.githubusercontent.com/algolia/datasets/master/movies/actors.json

// Get the 10th item in an array
cat actors.json | jq '.[10]'
// {
//   "name": "Dwayne Johnson",
//   "rating": 1568,
//   "image_path": "/akweMz59qsSoPUJYe7QpjAc2rQp.jpg",
//   "alternative_name": "The Rock",
//   "objectID": "551486400"
// }

// Get a property from the 10th item in array
// > "Dwayne Johnson"

// Get multiple items
jq '.[10:12]'

// Get items up to the 12th position
jq '.[:12]'

// Get items after the 12th position
jq '.[12:]'

// Get an array of properties from all objects
jq '.[].name'
// > ["William Shatner", "Will Ferrell", ...]

// Create an object with only properties I want
jq '{ name: .[].name, rating: .[].rating}'

// Built in functions!
jq 'sort'
jq 'length'
jq 'reverse'

There are loads of other ways to use jq, so I highly recommend you check out JQ Select Explained: Selecting elements from JSON. I'll keep jq handy for the foreseeable future, as it will be invaluable!

Recent Features

  • By
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

  • By
    39 Shirts – Leaving Mozilla

    In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...

Incredible Demos

  • By
    Sexy Opacity Animation with MooTools or jQuery

    A big part of the sexiness that is Apple software is Apple's use of opacity. Like seemingly every other Apple user interface technique, it needs to be ported to the web (</fanboy>). I've put together an example of a sexy opacity animation technique...

  • By
    Create an Animated Sliding Button Using MooTools

    Buttons (or links) are usually the elements on our sites that we want to draw a lot of attention to. Unfortunately many times they end up looking the most boring. You don't have to let that happen though! I recently found a...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!