[index][raw][main]
[noise@unvalidatedinput]$ man jq
jq(1) User Manuals jq(1)
NAME
jq
Sun Oct 8 16:16:06 BST 2017
DESCRIPTION
jq can transform JSON in various ways, by selecting, iterating, reducing and otherwise
mangling JSON documents.
It reads a stream of JSON entities from stdin and coupled with other Unix command line tools
like curl, grep, awk, sed allows a quick manipulation of APIs.
Cheatsheet
‐‐‐‐‐‐‐‐‐‐
[], {} array/object construction
length length of a value
keys keys in an array
, feed input into multiple filters
| pipe output of one filter to the next filter
select(foo) input unchanged if foo returns true
map(foo) invoke filter foo for each input
if‐then‐else‐end conditionals
\(foo) string interpolation
Let’s get JSON weather data from Open Weather Map API
$ json=$(curl ‐s ’https://samples.openweathermap.org/data/2.5/forecast?id=524901&appid=1’)
The returnet data is not human readable as the response is minified and returned in
a single line
$ echo $json | head ‐c 100
{"cod":"200","message":0.0036,"cnt":40,"list":[{"dt":1485799200,"main":{"temp":261.45,"temp_min"
This is where jq becomes handy. You can quickly format it using jq’s first argument which is a
"filter". The dot is perhaps the simplest of all jq filters. It matches the current input.
$ echo ${json} | jq . | head
{
"cod": "200",
"message": 0.0036,
"cnt": 40,
"list": [
{
"dt": 1485799200,
"main": {
"temp": 261.45,
"temp_min": 259.086,
The builtin function keys, when given json, returns its keys in an array.
$ echo ${json} | jq ’keys’
[
"city",
"cnt",
"cod",
"list",
"message"
]
Now you can filter on keys and display values:
$ echo ${json} | jq .city
{
"id": 524901,
"name": "Moscow",
"coord": {
"lat": 55.7522,
"lon": 37.6156
},
"country": "none"
}
You can nest the keys:
$ echo ${json} | jq .city.name
"Moscow"
Now the list element repeats and we have 40 entries:
echo ${json} | jq ’.list | length’
40
You can list them all selecting a sub key only:
echo ${json} | jq .list[].wind | head
{
"speed": 4.77,
"deg": 232.505
}
{
"speed": 4.76,
"deg": 240.503
}
{
"speed": 4.71,
You can selectively list an item, e.g. the last one:
$ echo ${json} | jq ’.list[39].wind’
{
"speed": 2.47,
"deg": 180.501
}
You can feed input into mulitple filters with ",":
echo ${json} | jq ’.cod, .cnt’
"200"
40
Instant schema:
echo ${json} | jq ‐r ’path(..) | map(tostring) | join ("/")’ | head
cod
message
cnt
list
list/0
list/0/dt
list/0/main
list/0/main/temp
list/0/main/temp_min
Linux March 2019 jq(1)
[noise@unvalidatedinput]$ ∎