jq - Technological watch

Learn what is jq in less than 5 minutes !
Friday, November 10, 2023

Problematic

Working with JSON files often presents challenges when it comes to locating and manipulating data. While most modern Linux systems offer powerful text processing tools like sed, awk, and grep, using them to parse JSON can be error-prone. And when it comes to modifying JSON content, the process can become especially difficult.

About the jq tool

jq is a lightweight and powerful command-line tool designed for parsing, querying, and transforming JSON data. It provides a concise and expressive way to filter and manipulate JSON.

Installation

Installing jq is straightforward and varies depending on your operating system. Here are the installation instructions for popular platforms:

  1. Linux (Debian/Ubuntu):
Terminal window
sudo apt-get install jq
  1. Linux (Fedora/RHEL):
Terminal window
sudo yum install jq
  1. macOS (via Homebrew):
Terminal window
brew install jq

Key jq commands

Now that you have jq installed, let’s explore some key commands that will help you tackle common JSON data manipulation tasks:

  1. Basic JSON parsing:
Terminal window
jq '.' file.json

or

Terminal window
echo '[{"name":"Alexandre","age":24},{"name":"Hugo","age":25},{"name":"Vincent","age":23}]' | jq '.'
# Output
# [
# { "name": "Alexandre", "age": 24 },
# { "name": "Hugo", "age": 25 },
# { "name": "Vincent", "age": 23 }
# ]

This command will pretty-print the JSON file, making it more human-readable. Replace ’.’ with specific selectors to extract only the data you need.

  1. Filtering JSON objects:
Terminal window
jq '.key' file.json

Replace .key with the specific key you want to extract from the JSON data.

  1. Iterating over arrays:
Terminal window
jq '.array[]' file.json

Use this command to extract all elements from a JSON array.

  1. Complex queries:
Terminal window
jq '.items[] | select(.price < 20)' file.json

This example filters items with a price less than 20 from a JSON array.

  1. Modifying JSON data:
Terminal window
jq '.key = "new_value"' file.json

This command can be used to update the value of a specific key.

More information

Whether you are a developer, data analyst, or system administrator, “jq” is a valuable addition to your toolkit, simplifying JSON data processing and making your work more productive and less error-prone.

More informations here:


Recommended articles