The JSON data format has conquered the world of development. It has the advantage of being human-readable and is supported by most programming languages.

Perfect ? Are you really sure?  Have you ever tried to manipulate JSON in a shell?

You understand  why you are in this page.

This article answer  on the tools who we can uses the same ease that sed, awk, grep. There are 2 tools good for JSON :

  • jq : un sed pour JSON
  • jsawk : un awk pour JSON

I  focus in this article on JQ :

Installation

On macOS  install using

$ brew install jq

Capture-d-e-cran-2018-12-25-a--02.42.52

On  Linux  install JQ using

# Debian and Ubuntu 
    $ sudo apt-get install jq.
# Fedora 
    $ sudo dnf install jq.
# openSUSE
    $ sudo zypper install jq

On Windows  install JQ using  Chocolatey NuGet :

$ chocolatey install jq

Parse JSON data using jq and curl from command line :

Let's, start this tools JQ by parse JSON result of using 2 samples API:

Airports API:

https://airport-web.appspot.com/api/docs/

$ curl -s  "https://airport-web.appspot.com/_ah/api/airportsapi/v1/airports/EDDB"

{
"ICAO": "EDDB",
"last_update": "2015-12-03T18:57:24.730180",
"name": "Flughafen Berlin-Sch\u00f6nefeld",
"url": "http://www.berlin-airport.de/"
}

# To show just the airport name and url :
$ curl -s  "https://airport-web.appspot.com/_ah/api/airportsapi/v1/airports/EDDB" | jq '.name,.url'

Capture-d-e-cran-2018-12-25-a--04.34.36

jq '.'

Capture-d-e-cran-2018-12-25-a--04.38.32

Docker Engine API

For example to list docker containers running in my machine I run :

$ curl --unix-socket /var/run/docker.sock http:/v1.39/images/json 

The Output

[{"Containers":-1,"Created":1545710457,
"Id":"sha256:9a8842c916db019db1edcf25b9e2e0dee94b52fe8be2d03c4fcba807b9ce3c46","Labels":{"Description":"This is docker image of Rest Micro-Service Books","PROJECT_NAME":"micro-service-book","Vendor":"API Books","Version":"1.0","maintainer":"cherara.reddah@icloud.com"},"ParentId":"sha256:f7e023da79af151a8f5002bff7c5f64dbb3b1103ca8f8bf491572493d57227b6","RepoDigests":null,"RepoTags":["mydockerreddah/micro-service-book:latest"],"SharedSize":-1,"Size":486360844,"VirtualSize":486360844},
.....

The result is illegible and hard to find a specific container

# show the firts container
$ curl --unix-socket /var/run/docker.sock http:/v1.39/images/json | jq '.[0]'

Capture-d-e-cran-2018-12-25-a--04.40.56

$ curl --unix-socket /var/run/docker.sock http:/v1.39/images/json | jq '.[5]'
$ curl --unix-socket /var/run/docker.sock http:/v1.39/images/json | jq '.[5]' | jq '.Id, .Labels[],.Size'

Capture-d-e-cran-2018-12-25-a--04.55.28

Online tool to test JQ filters.

https://jqplay.org/