Code & computing / QUICK REFERENCE

jq JSON essentials

Select, reshape, filter and summarize JSON with small shell-friendly examples.

24 entries

Inspect and select

Pretty-print JSON
jq '.' data.json

Parses input and formats each JSON value. [2]

Select a property
jq '.name' data.json

Missing object keys generally produce null. [2]

Nested property
jq '.user.name' data.json

Input structure must support the path. [2]

First array element
jq '.[0]' data.json

Indexes are zero-based. [2]

Last array element
jq '.[-1]' data.json

Negative index counts backward. [2]

Iterate array values
jq '.[]' data.json

Emits each element as a separate result. [2]

Array slice
jq '.[1:4]' data.json

The end index is excluded. [2]

Raw string output
jq -r '.name' data.json

Removes JSON string quoting, not arbitrary escaping for a shell. [2]

Filter and reshape

Project two fields
jq '{name, count}' data.json

Creates a new object using these keys. [1]

Rename a field
jq '{label: .name}' data.json

Constructs a differently named output property. [1]

Keep matching objects
jq '.[] | select(.active == true)' data.json

select emits only values satisfying the test. [1]

Map an array
jq 'map(.name)' data.json

Returns an array of each element's name. [1]

Count elements
jq 'length' data.json

Meaning depends on the input type. [1]

List object keys
jq 'keys' data.json

Sorts object keys. [1]

Sorted objects
jq 'sort_by(.name)' data.json

Expects an array. [1]

Deduplicate values
jq 'unique' data.json

Sorts and removes duplicate array values. [1]

Practical composition

Fallback value
jq '.name // "unknown"' data.json

// also uses the fallback for false, not only null. [1]

Check key presence
jq 'has("name")' data.json

Distinguishes missing keys from an explicit null value. [1]

Pass a string safely
jq --arg wanted 'Atlas' '.[] | select(.name == $wanted)' data.json

--arg avoids injecting shell text into filter syntax. [1]

Pass a JSON value
jq --argjson limit 3 '.[:$limit]' data.json

--argjson parses its argument as JSON. [1]

Compact output
jq -c '.' data.json

Emits compact JSON values. [1]

Slurp a stream
jq -s '.' data.json

Reads input values into one array; memory use grows with input. [1]

Create JSON without input
jq -n --arg name 'Atlas' '{name: $name}'

Avoids string-concatenating a JSON document. [1]

Fail on false/null result
jq -e '.active == true' data.json

Exit status depends on the last result; handle empty output too. [1]

Reserved placement, separate from reference controls. No ad network is active.

Updated jq · core filters / POSIX shell quoting

Sources

  1. jq manual ↗
  2. jq tutorial ↗