Skip to content

jq tricks

Get values from array of maps:

cat << EOF > s
[ 
 { "id": "144", "name": "foo"}, 
 { "id": "628", "name": "bar"} 
]
EOF
#
cat s | jq -r '.[] | "\(.name) \(.id)"'
#
foo 144
bar 628

Show map

cat << EOF > s
{ 
 "id":"2222222",
 "release":"1.23",
 "hostname":"srv-1"
}
EOF
#
cat s | jq 'to_entries[] | "\(.key): \(.value)"' | tr -d '"'
#
id: 2222222
release: 1.23
hostname: srv-1

Return empty string, if value not found

cat << EOF > s
{ 
  "name": "aaa", 
  "host": "server", 
  "id": "kkkk" 
}
EOF
# don't return 'null'
cat s | jq ".header // empty"
#

Search by field value

cat << EOF > s
[ 
 { "id": "144", "name": "foo"}, 
 { "id": "628", "name": "bar"} 
]
EOF
#
cat s  | jq '.[] | select(.name == "bar")'
# result
{
  "id": "628",
  "name": "bar"
}