jq चीटशीट

1.7

JSON wrangling के लिए ज़रूरी jq filters और expressions

हिन्दी: 2026-03-29

jq JSON के लिए sed है — एक lightweight, flexible command-line processor जो messy API responses और config files को बिलकुल उस data में बदल देता है जो आपको चाहिए। अगर आपने कभी minified JSON की दीवार में घूरते हुए एक nested field ढूंढने की कोशिश की है, तो jq वह tool है जो आपको सोचने पर मजबूर करेगा कि इसके बिना कैसे काम चलता था।

Mental model सीधा है: jq एक pipeline है। Data बाएँ से आता है, filters से transform होता है, और दाईं तरफ निकलता है। . आपका starting point है — इसका मतलब है "पूरा input।" वहाँ से .field से drill down करें, .[] से iterate करें, और | से filters chain करें। यह functional programming है जो command-line tool जैसी दिखती है, और एक बार pipe-thinking click हो जाए, तो आप jq के लिए वैसे ही हाथ बढ़ाएंगे जैसे grep के लिए बढ़ाते हैं।

हमने इसे jq की internal taxonomy के बजाय उस तरह की problem के अनुसार organize किया है जो आप solve कर रहे हैं। JSON से values निकालने के लिए Basic Filters से शुरू करें, फिर जब data reshape करना हो तो Array और Object Operations पर जाएँ। आखिर में One-Liners section में असली magic है — battle-tested patterns जो आप अभी अपने terminal में copy-paste कर सकते हैं।

एक बात जल्दी internalize करें: jq expressions composable हैं। हर filter input लेता है और output produce करता है, इसलिए आप इन्हें | से अंतहीन chain कर सकते हैं। वह select(...) जो आपने लिखा? इसे map(...) में pipe करें। उसे sort_by(...) में pipe करें। Filters ही filters हैं, बस।

Basic Filters
.
Identity — पूरा input unchanged output करें
.field
नाम से top-level field extract करें
.field.nested
Dot notation से nested objects में drill करें
.["hyphenated-key"]
नाम में special characters वाले fields access करें
.[]
Array के सभी elements या object की सभी values पर iterate करें
.[0]
Array का पहला element लें
.[-1]
Array का आखिरी element लें
.[2:5]
Array slice करें — index 2, 3, और 4 के elements
.field?
Field access try करें — exist नहीं करने पर errors suppress करें
.[] | .name
Array iterate करें और हर element से field extract करें
Types और Values
null
JSON null value
length
String length, array count, या object keys की संख्या
keys
Object के सभी keys sorted array के रूप में लें
keys_unsorted
Object के सभी keys original order में लें
values
Object की सभी values array के रूप में लें
type
Type string के रूप में return करें: "object", "array", "string", "number", "boolean", या "null"
has("field")
Check करें कि object में specific key है या नहीं (true/false return करता है)
in({"a":1})
Check करें कि key दिए गए object में exist करती है
empty
कोई output produce न करें — conditional suppression के लिए उपयोगी
env.VAR
Environment variable VAR access करें
String Operations
split(",")
Delimiter से string split करके array बनाएँ
join(",")
Strings के array को delimiter से join करें
test("regex")
Test करें कि string regex से match करती है (true/false return करता है)
match("regex")
Offset, length, और captures के साथ match object return करें
capture("(?<name>\\w+)")
Named capture groups object के रूप में return हों
gsub("old"; "new")
Regex pattern की सभी occurrences replace करें
sub("old"; "new")
Regex pattern की पहली occurrence replace करें
ascii_downcase
String lowercase में convert करें
ascii_upcase
String uppercase में convert करें
ltrimstr("prefix")
String से prefix हटाएँ अगर मौजूद हो
rtrimstr("suffix")
String से suffix हटाएँ अगर मौजूद हो
@base64
String को base64 में encode करें
@base64d
Base64 string decode करें
@uri
URLs के लिए string percent-encode करें
@html
HTML special characters escape करें
tostring
किसी भी value को string representation में convert करें
tonumber
String को number के रूप में parse करें
Array Operations
map(f)
हर element पर filter f apply करें और results collect करें
map_values(f)
हर value पर filter f apply करें (objects पर भी काम करता है)
select(condition)
सिर्फ वे elements रखें जहाँ condition true हो
sort
Comparable values का array sort करें
sort_by(.field)
Objects के array को specific field से sort करें
reverse
Array का order reverse करें
group_by(.field)
Array elements को field से sub-arrays में group करें
unique
Sorted array से duplicate values हटाएँ
unique_by(.field)
Specific field से duplicates हटाएँ
flatten
Nested arrays को single level में flatten करें
flatten(1)
एक level की nesting flatten करें
first
Generator से पहला output लें
last
Generator से आखिरी output लें
limit(n; expr)
Expression से सिर्फ पहले n outputs लें
add
Numbers जोड़ें, strings concatenate करें, या arrays/objects merge करें
any(condition)
True अगर कोई भी element condition satisfy करे
all(condition)
True अगर सभी elements condition satisfy करें
min_by(.field)
सबसे छोटी field value वाला element लें
max_by(.field)
सबसे बड़ी field value वाला element लें
indices(value)
Array में जहाँ value appear होती है वे सभी indices लें
contains([values])
Check करें कि array में सभी specified values हैं
inside([values])
Check करें कि input दिए गए value में contained है
Object Operations
to_entries
{"a":1} को [{"key":"a","value":1}] में convert करें
from_entries
[{"key":"a","value":1}] को वापस {"a":1} में convert करें
with_entries(f)
to_entries | map(f) | from_entries का shorthand
+ (objects)
दो objects merge करें — key conflicts में right side जीतता है
* (objects)
दो objects recursively merge करें
{name, age}
Object से specific fields select करें
{newname: .oldname}
Extract करते समय field rename करें
del(.field)
Object से field हटाएँ
paths
Leaf values तक सभी paths arrays के रूप में list करें
getpath(["a","b"])
Specific path पर value लें — .a.b जैसा
setpath(["a","b"]; val)
Specific path पर value set करें
delpaths([path])
Specified paths पर values delete करें
Conditionals और Comparisons
if . then A else B end
Conditional expression — else clause optional है
// (alternative)
Left null या false हो तो right value इस्तेमाल करें
a == b
Equality comparison (objects/arrays के लिए deep equality)
a != b
Inequality comparison
and, or, not
Boolean operators
try f
Filter f चलाएँ, errors चुपचाप suppress करें
try f catch msg
Filter f चलाएँ, error पर msg expression इस्तेमाल करें
f as $var | expr
Pipeline में इस्तेमाल के लिए value को variable में bind करें
reduce .[] as $x (init; update)
Array को single value में fold करें
label $out | foreach ...
Break support के साथ streaming loop
Output Formatting
-r (--raw-output)
JSON quotes के बिना raw strings output करें
-c (--compact-output)
Minify — JSON single line पर print करें
-S (--sort-keys)
Output में object keys alphabetically sort करें
-e (--exit-status)
Output के आधार पर exit code set करें: true/non-null के लिए 0, false/null के लिए 1
-n (--null-input)
Input न पढ़ें — --argjson या --slurpfile के साथ उपयोगी
-s (--slurp)
सभी inputs एक single array में पढ़ें
--arg name val
String value को $name variable के रूप में pass करें
--argjson name val
JSON value को $name variable के रूप में pass करें
--slurpfile name file
JSON file को $name variable (array) के रूप में load करें
@csv
Arrays के array को CSV format में बदलें
@tsv
Arrays के array को TSV format में बदलें
@json
Value को JSON string के रूप में serialize करें (embedding के लिए)
@text
Text output में convert करें

One-Liners

Real-world patterns जो आप वाकई इस्तेमाल करेंगे। Copy करें, paste करें, adapt करें।

One-Liners
jq . file.json
JSON file pretty-print करें
jq -r ".[] | .name" file.json
Array में हर object से field extract करें
jq "[.[] | select(.active == true)]"
Array को सिर्फ matching elements तक filter करें
jq -r ".[] | [.name, .email] | @csv"
JSON array को CSV में convert करें
jq -s "." file1.json file2.json
Multiple JSON files को एक array में merge करें
jq -r "keys[]" file.json
सभी top-level keys list करें
jq ".[] | select(.price > 100) | .name"
वे names ढूंढें जहाँ price threshold से ज़्यादा हो
jq "group_by(.status) | map({(.[0].status): length}) | add"
हर group में items count करें
jq --arg q "$QUERY" '.[] | select(.name | test($q; "i"))'
Shell variable इस्तेमाल करके case-insensitive search
jq -r "to_entries[] | \"\(.key)=\(.value)\""
JSON object को key=value lines में convert करें
jq "[.[] | {id, name}]"
Objects reshape करें — सिर्फ specific fields रखें
jq -r ".results | sort_by(.date) | reverse | .[0]"
Sorted array से सबसे recent entry लें
curl -s api.example.com | jq .
API response inline pretty-print करें
jq -s "map(.items) | flatten | unique_by(.id)"
Paginated API responses merge और deduplicate करें
jq 'walk(if type == "string" then gsub("\\n"; " ") else . end)'
सभी string values में recursively newlines clean up करें

जब भी आप jq को दूसरे command में pipe करें, -r (raw output) इस्तेमाल करें। इसके बिना, strings quotes में wrapped आती हैं, और वे quotes आपकी shell scripts में problems create करेंगे। jq -r '.name' आपको Alice देता है, "Alice" नहीं।

// operator jq का null coalescing है — left null या false हो तो right side return करता है। Defaults के लिए perfect: .config.timeout // 30। यह दो-character combo है जो 90 प्रतिशत बार आपको पूरा if-then-else लिखने से बचाता है।

जब आपको multiple files या API responses से data combine करना हो, --slurp (-s) इस्तेमाल करें। यह सभी inputs एक single array में पढ़ता है, ताकि आप objects add कर सकें, arrays flatten कर सकें, या files में data zip कर सकें।

Shell variables को jq में safely pass करने के लिए --arg और --argjson इस्तेमाल करें। Shell variables सीधे jq expressions में कभी interpolate न करें — special characters पर break होता है और injection का खतरा होता है। jq --arg name "$USER" '.[] | select(.name == $name)' सही तरीका है।

Kubernetes secrets या JWTs के साथ काम करते समय @base64d filter lifesaver है। Base64-encoded value को jq -r '.data.password | @base64d' से pipe करें और pipeline छोड़े बिना plaintext पाएँ।

Object keys और values को एक ही pass में transform करने के लिए to_entries, map, और from_entries (या shorthand with_entries) chain करें। हर key में prefix चाहिए? with_entries(.key = "prefix_" + .key)। यह arrays के लिए map का object equivalent है।

अगर jq के error messages cryptic लगें, तो अपनी pipeline में कहीं भी debug जोड़ दें ताकि देख सकें कि उस point पर क्या flow हो रहा है। यह output disturb किए बिना stderr पर print करता है। इसे jq का console.log समझें: .[] | debug | select(.active)

Related Tools