Back to Blog

Working with JSON in Zsh — jq Basics, Filters & Practical #22

Sandy LaneSandy Lane

Video: Working with JSON in Zsh — jq Basics, Filters & Practical #22 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Working with JSON in Zsh — jq Basics, Filters & Practical

Mastering JSON processing in the Zsh shell is straightforward with the powerful jq tool. This guide introduces jq's core features, from pretty printing JSON to advanced filtering, transforming, and output formatting techniques that simplify handling JSON data on the command line.

Code

# Pretty print JSON from a file
jq '.' data.json

# Extract a single field from JSON object
jq '.name' data.json

# Access the first element of a JSON array
jq '.[0]' data.json

# Iterate over all elements in a JSON array
jq '.[]' data.json

# Access nested fields
jq '.user.address.city' data.json

# Output raw strings without quotes
jq -r '.user.name' data.json

# Chain filters: get names of users older than 30
jq '.users | map(select(.age > 30)) | .[].name' data.json

# Count elements in an array or keys in an object
jq '.users | length' data.json
jq 'keys' data.json

# Slice an array: first 3 elements
jq '.users[:3]' data.json

# Check type of a JSON value
jq 'type' data.json

# Construct a new JSON object with selected fields
jq '{username: .user.name, city: .user.address.city}' data.json

# String interpolation inside jq
jq -r '"User: \(.user.name), City: \(.user.address.city)"' data.json

# Sort array by a field and reverse order
jq '.users | sort_by(.age) | reverse' data.json

# Output JSON array as CSV
jq -r '.users | map([.name, .age]) | @csv' data.json

# Count filtered results: number of users older than 25
jq '[.users[] | select(.age > 25)] | length' data.json

Key Points

  • Use jq '.' to pretty print JSON data for better readability in the terminal.
  • Dot notation and array indexing enable easy extraction of nested fields and elements.
  • Filters like select() and map() allow powerful querying and transformation of JSON arrays.
  • jq supports constructing new JSON objects and string interpolation for custom output formatting.
  • Advanced features include sorting, slicing, type checking, and exporting JSON data as CSV.