Master JSON Formatting and Extraction on Linux with jq
This guide explains what jq is, how to install it on various Linux distributions, and provides step‑by‑step examples for pretty‑printing JSON, extracting specific fields, handling arrays, and using built‑in functions like keys and has, all with clear command‑line snippets.
What is jq?
jq is a lightweight command‑line utility for parsing, filtering and transforming JSON data. It reads JSON from stdin, files or pipelines and writes the result to stdout, making it easy to embed in shell scripts.
Installation on Linux
Most distributions provide jq in their package repositories. Install it with the appropriate package manager:
Arch Linux: sudo pacman -S jq Debian/Ubuntu/Mint: sudo apt-get install jq Fedora: sudo dnf install jq OpenSUSE: sudo zypper install jq For other distributions consult the official installation guide.
Formatting JSON for readability
Save the raw JSON to a file (e.g., liangxu.json) and run: cat liangxu.json | jq '.' The “.” filter outputs the input unchanged but pretty‑prints it with indentation.
Extracting specific fields
To retrieve the address object: jq .address liangxu.json To get the nested postalCode value: cat liangxu.json | jq .address.postalCode Filters are case‑sensitive; field names must match exactly.
Working with arrays
The phoneNumber field is an array. To list all elements: jq .phoneNumber[] liangxu.json To fetch the first element only:
jq .phoneNumber[0] liangxu.jsonBuilt‑in functions
Two useful jq functions are demonstrated:
keys – lists all top‑level keys: cat liangxu.json | jq 'keys' has – tests for the presence of a key, returning true or false:
cat liangxu.json | jq 'has("alvin")'Conclusion
jq covers basic formatting and extraction, and also supports arithmetic, conditionals, variable declarations and custom functions. Readers are encouraged to explore the official jq manual for advanced usage.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
