Tips&Tricks

How to get a field from JSON HTTP response in Bash

jq – is a powerful tool for working with JSON in Bash. It can do more than just get a field. But in this note we’ll not describe all of its might. You should read more about jq if you write in Bash a lot.

Ok, let’s move! For example we have following response:

$ curl -s https://status.github.com/api/status.json
{"status":"good","last_updated":"2018-07-20T09:55:21Z"}

So we can get one field from this response:

$ curl -s https://status.github.com/api/status.json | jq '.status'
"good"

For more fields you can use this snippet:

$ curl -s https://status.github.com/api/status.json | jq --raw-output '.status,.last_updated'
good
2015-01-21T17:02:57Z

A few more jq examples

Output a JSON file, in pretty-print format:

cat {{file}} | jq

Output all elements from arrays (or all key-value pairs from objects) in a JSON file:

cat {{file}} | jq .[]

Read JSON objects from a file into an array, and output it (inverse of jq .[]):

cat {{file}} | jq --slurp

Output the first element in a JSON file:

cat {{file}} | jq .[0]

Output the value of a given key of the first element in a JSON file:

cat {{file}} | jq .[0].{{key_name}}

Output the value of a given key of each element in a JSON file:

cat {{file}} | jq 'map(.{{key_name}})'