Advanced JQ Patterns

February 03, 2023

Unlocking the Power of JQ: A Guide to Advanced JQ Patterns for Manipulating JSON Data

JQ is a command-line tool for processing JSON data, allowing developers to filter, transform, and extract information from complex JSON structures with ease. While its basic usage is straightforward, JQ is capable of much more advanced transformations and manipulations of JSON data, making it a valuable tool for anyone working with JSON data. In this post, we will explore some of the most powerful JQ patterns for transforming and manipulating JSON data.

  1. Filtering JSON objects based on the value of a specific key:
jq '.servers[] | select(.role == "backend") | .ip'

filter-by example playground

  1. Sorting JSON objects by key value:
jq '.countries | sort_by(.population) | reverse | .[] | .name'

sort-by example playground

  1. Grouping JSON objects based on a key value:
jq '.calls | group_by(.route) | map({key: .[0].route, value: map(.path)})'

group-by example playground

  1. Flattening nested JSON objects:
jq '.people[].address[]'
  1. Merging multiple JSON objects into one
jq --slurp 'reduce .[] as $item ({}; . * $item)'
  1. Transforming JSON data into a different format:
jq '.people[] | {name: .name, city: .address[].city}'

How to get started with JQ

  1. read the official documentation
  2. install JQ
  3. try and share your queries in our JQ playground
  4. follow the interactive tutorial to learn JQ