JSON Processing Should Not Require Python
jq processes JSON on the command line. Pipe any API response through it for instant formatting, filtering, and transformation.
Basics
# Pretty print
curl -s https://api.github.com/users/torvalds | jq .
# Get one field
curl -s https://api.github.com/users/torvalds | jq .name
# "Linus Torvalds"
# Get nested field
curl -s https://api.github.com/users/torvalds | jq .company
Filter Arrays
# Get names from array
echo '[{"name":"a","age":20},{"name":"b","age":30}]' | jq '.[].name'
# Filter
echo '[{"name":"a","age":20},{"name":"b","age":30}]' | jq '.[] | select(.age > 25)'
# Map
echo '[1,2,3,4,5]' | jq '[.[] * 2]'
# [2,4,6,8,10]
API Examples
# GitHub: get repo names and stars
curl -s "https://api.github.com/users/torvalds/repos" | jq '.[] | {name, stars: .stargazers_count}' | head -20
# npm: get package version
curl -s https://registry.npmjs.org/express | jq '.["dist-tags"].latest'
# Count items
curl -s "https://api.github.com/users/torvalds/repos" | jq length
Transform Data
# CSV from JSON
echo '[{"name":"a","age":20},{"name":"b","age":30}]' | jq -r '.[] | [.name, .age] | @csv'
# Build new objects
echo '{"first":"John","last":"Doe","age":30}' | jq '{full_name: (.first + " " + .last), age}'
Install: brew install jq or apt install jq. You will use it every day.
More from me: 10 Dev Tools I Use Daily | 77 Scrapers on a Schedule | 150+ Free APIs
Top comments (0)