Quick Linux Tip #54 - Extract JSON Values with jq

Quick Linux Tip #54:

Question: How do I quickly grab a value from JSON output on the command line?

Try: curl -s https://api.github.com/users/torvalds | jq -r '.name, .public_repos, .followers'

Info: jq is a powerful command-line JSON processor. The -r option outputs strings without quotes, while jq filters can extract, filter, map, and transform JSON data.

Examples:

  • $ jq '.users[] | select(.active == true)' data.json  # Filter active users
  • $ kubectl get pods -o json | jq -r '.items[].metadata.name'  # Extract Kubernetes pod names
  • $ jq '.[]' file.json  # Iterate over a JSON array

Note: Install jq with sudo apt install jq. Use jq filters to extract exactly the fields you need when working with REST APIs, Kubernetes output, or configuration files. For complex filters, test them against sample JSON before using them in production scripts.




LinuxTeck.com
linuxteck@ubuntu:~$ curl -s https://api.github.com/users/torvalds | jq -r '.name, .public_repos, .followers'
Linus Torvalds
8

linuxteck@ubuntu:~$ docker inspect nginx | jq -r '.[0].NetworkSettings.IPAddress'
172.17.0.2

linuxteck@ubuntu:~$ curl -s https://api.github.com/repos/torvalds/linux | jq '{name, stars: .stargazers_count}'
{
  "name": "linux",
  "stars": 178945
}
linuxteck@ubuntu:~$

PREVIOUS ARTICLE Quick Linux Tip #53: I have many processes matching a pattern. How do I kill them all at once? NEXT ARTICLE Quick Linux Tip #55 - Check Exported Symbols in .so Files
About John Britto

John Britto Founder & Chief-Editor @LinuxTeck. A Computer Geek and Linux Intellectual having more than 20+ years of experience in Linux and Open Source technologies.

View all posts by John Britto →

Leave a Reply

Your email address will not be published.