long

JQ

jq enables many pretty printing possibilities.

$ echo '[1,2,4,5]' | jq
[
  1,
  2,
  4,
  5
]

Practical example: nodejs latest LTS download

I want a script to always download the latest LTS from nodejs.

Nodejs does not provide a pointer to the latest LTS, latest points to the "bleeding edge", 14 at time of writing.

Hopefully nodejs team provides a json file that we will parse which lists all the existing versions in reverse order.

$ curl -sS https://nodejs.org/dist/index.json | jq
[
  {
    "version": "v14.2.0",
    "date": "2020-05-05",
    "files": [
      "aix-ppc64",
      "headers",
      "linux-arm64",
      "linux-armv7l",
      "linux-ppc64le",
      "linux-s390x",
      "linux-x64",
      "osx-x64-pkg",
      "osx-x64-tar",
      "src",
      "win-x64-7z",
      "win-x64-exe",
      "win-x64-msi",
      "win-x64-zip",
      "win-x86-7z",
      "win-x86-exe",
      "win-x86-msi",
      "win-x86-zip"
    ],
    "npm": "6.14.4",
    "v8": "8.1.307.31",
    "uv": "1.37.0",
    "zlib": "1.2.11",
    "openssl": "1.1.1g",
    "modules": "83",
    "lts": false,
    "security": false
  },
  ---8<--- truncated ---8<---
]

To be able to retreive the version we can filter with .[].version:

$ curl -sS https://nodejs.org/dist/index.json | jq '.[].version'
"v14.2.0"
"v14.1.0"
"v14.0.0"
"v13.14.0"
"v13.13.0"
"v13.12.0"
---8<--- truncated ---8<---

This is not helping a lot as we have no clue which is the LTS. Hopefully, the lts property is "not false" when the version is an LTS -- each has a name.

Here comes some magic:

$ curl -sS https://nodejs.org/dist/index.json | jq 'map(select(.lts != false)) | .[0].version'
"v12.16.3"

jq will loop through the items of the original array, apply the requested filter (lts attribute not being false), create an array with the results, pass it further (the pipe "|") to take the first entry's version attribute.

The quotes are part of the result. To be able to use it, we need to remove them:

$ version=$(curl -sS https://nodejs.org/dist/index.json | jq -r 'map(select(.lts != false)) | .[0].version')
$ echo $version
v12.16.3

This can now be used to download the corresponding nodejs package.

More example probably soon.

jq's documentation is on its website

About me

Stuff I do with my brain, my fingers and an editor:

(Front-end) development - typescript, Vue, React, svelte(kit) web architectures web performance API design pragmatic SEO security Accessibility (A11y) front-end dev recruitment and probably more...

Feel free to , check out my open source projects, or just read the things I write on this site.