Skip to content

jq

jq is a lightweight and flexible command-line json processor.

Things I love about jq.

  • can pipe output from various sources in terminal.

    // common use cases with curl and cat
    curl 'https://api.github.com/repos/jqlang/jq/commits?per_page=5' | jq .
    
    cat myjson.json | jq .
    
  • cool tooling. zsh plugin, repl with fzf

  • can use it inside vim

Sources

Usage Cheatsheet

Common command line options

  1. -c/--compact-output
  2. -r/--raw-output
  3. -S/--sort-keys

Common Filters

Identity

. - takes input and produces same values as output

Example
echo '{"foo": 42, "bar": "less interesting data"}' | jq '.'
//output
{
  "foo": 42,
  "bar": "less interesting data"
}

Object Identifier Index

.key1, .key1.key11 or .key1 | .key11

Example
Example 1
echo '{"foo": 42, "bar": "less interesting data"}' | jq '.foo'
//output
42

Example 2

// Optional Identifier
echo '{"foo": 42, "bar": "less interesting data"}' | jq '.id?'
//output
null

Example 3

echo '{"foo": {"id": 42, "bar": "less interesting data"}}' | jq '.foo.bar'
//output
"less interesting data"

Object Index

.[<string>] = .["foo"], .foo is better shorthand

Array Index

Example

.[index]

echo '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]' | jq '.[0]'
//output
{
  "name": "JSON",
  "good": true
}

Pipe

| : combines two filters

Example
echo '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]' | jq '.[] | .name'
//Input
[
  {
    "name": "JSON",
    "good": true
  },
  {
    "name": "XML",
    "good": false
  }
]

//Output
"JSON"
"XML"

More Here

Basic Filters | Man Page

Common Builtin Operators and functions

Common mathematical operations (add, substract, multiply, divide, absolute value, sqrt)

Length

Example
echo '{"foo": [1, 2, 3], "bar": "hello"}' | jq '.foo | length'
// Output
3

Keys

Example
echo '{"foo": 42, "bar": "value"}' | jq 'keys'
// Output
["bar", "foo"]

has(keys)

map(f)

Example
echo '[1, 2, 3]' | jq 'map(. * 10)'
//Output
[10, 20, 30]

select(boolean_expression)

Example
echo '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 20}]' | jq '.[] | select(.age > 25)'
// Input
[
  { "name": "Alice", "age": 30 },
  { "name": "Bob", "age": 20 }
]
// Output
{
  "name": "Alice",
  "age": 30
}

More Here

Builtin Operators and Function

Common Data Types

Object Construction {}

Example
Command	jq '{user, title: .titles[]}'
Input	{"user":"stedolan","titles":["JQ Primer", "More JQ"]}
Output	{"user":"stedolan", "title": "JQ Primer"}
{"user":"stedolan", "title": "More JQ"}


Command	jq '{(.user): .titles}'
Input	{"user":"stedolan","titles":["JQ Primer", "More JQ"]}
Output	{"stedolan": ["JQ Primer", "More JQ"]}

Array Construction []

Example
echo '{"user":"stedolan", "projects": ["jq", "wikiflow"]}' | jq '[.user, .projects[]]'
// Input
{
  "user": "stedolan",
  "projects": ["jq", "wikiflow"]
}
//Output
["stedolan", "jq", "wikiflow"]