TExcelTAD
Home › JSON › Querying with jq

Querying with jq

jq is a small command-line program for slicing, filtering and transforming JSON — often described as "sed and grep for JSON". It's invaluable for exploring API responses, log files and config files without writing a script.

Note: jq can't run inside a browser, so the bash playgrounds on this page are simulated: they show the real output that jq 1.6 produced for each command. Install jq (apt install jq, brew install jq, or a download from the jq website) to try them yourself.

The sample file

All examples use this file, saved as products.json. Run it to check that it's valid:

json · try it yourself
{
  "store": "TAD Market",
  "products": [
    {"id": 1, "name": "Green Tea", "category": "drinks", "price": 4.5, "stock": 120, "tags": ["organic"]},
    {"id": 2, "name": "Rice Cooker", "category": "kitchen", "price": 59, "stock": 8, "tags": []},
    {"id": 3, "name": "Espresso Beans", "category": "drinks", "price": 24.5, "stock": 0, "tags": ["coffee", "organic"]},
    {"id": 4, "name": "Notebook", "category": "office", "price": 3.25, "stock": 300, "tags": ["paper"]}
  ]
}
Valid JSON: object with 2 keys
{
  "store": "TAD Market",
  "products": [
    {
      "id": 1,
      "name": "Green Tea",
      "category": "drinks",
      "price": 4.5,
      "stock": 120,
      "tags": [
        "organic"
      ]
    },
    {
      "id": 2,
      "name": "Rice Cooker",
      "category": "kitchen",
      "price": 59,
      "stock": 8,
      "tags": []
    },
    {
      "id": 3,
      "name": "Espresso Beans",
      "category": "drinks",
      "price": 24.5,
      "stock": 0,
      "tags": [
        "coffee",
        "organic"
      ]
    },
    {
      "id": 4,
      "name": "Notebook",
      "category": "office",
      "price": 3.25,
      "stock": 300,
      "tags": [
        "paper"
      ]
    }
  ]
}

How jq works

You give jq a filter (in single quotes) and some JSON input:

bash
jq '<filter>' products.json
cat products.json | jq '<filter>'

The simplest filter is . — "the whole input" — which pretty prints the file with colours. That alone makes jq worth installing.

Picking fields

.key selects a key, [n] an array item:

bash · try it yourself
jq '.store' products.json
"TAD Market"
bash · try it yourself
jq '.products[0]' products.json
{
  "id": 1,
  "name": "Green Tea",
  "category": "drinks",
  "price": 4.5,
  "stock": 120,
  "tags": [
    "organic"
  ]
}

Use -r (raw output) to print strings without quotes and -c (compact) to print each result on one line.

Iterating with [] and the pipe |

.products[] produces each item as a separate result. The pipe | feeds every result into the next filter, just like a shell pipe:

bash · try it yourself
jq -r '.products[] | .name' products.json
Green Tea
Rice Cooker
Espresso Beans
Notebook
bash · try it yourself
jq -c '.products[] | {id, stock}' products.json
{"id":1,"stock":120}
{"id":2,"stock":8}
{"id":3,"stock":0}
{"id":4,"stock":300}

{id, stock} is shorthand for {"id": .id, "stock": .stock} — a quick way to build a smaller object. Notice that -c output is JSON Lines.

Filtering with select()

select(condition) keeps only results where the condition is true:

bash · try it yourself
jq -r '.products[] | select(.price > 20) | .name' products.json
Rice Cooker
Espresso Beans
bash · try it yourself
jq -c '[.products[] | select(.category == "drinks" and .stock > 0) | .name]' products.json
["Green Tea"]

Wrapping a filter in [ ... ] collects all its results into one array.

Computing values

jq has many built-in functions: length, map, add, sort_by, group_by, keys, min_by, max_by and more.

bash · try it yourself
jq '.products | length' products.json
4
bash · try it yourself
jq '.products | map(.price) | add / length' products.json
22.8125
bash · try it yourself
jq -c '.products | group_by(.category) | map({category: .[0].category, count: length})' products.json
[{"category":"drinks","count":2},{"category":"kitchen","count":1},{"category":"office","count":1}]
bash · try it yourself
jq -c '[.products[] | select(.tags | contains(["organic"])) | .name]' products.json
["Green Tea","Espresso Beans"]

Strings and defaults

String interpolation uses \(...), and the alternative operator // supplies a default when a value is missing or null:

bash · try it yourself
jq -r '.products[] | "\(.id) - \(.name): \(.price)"' products.json
1 - Green Tea: 4.5
2 - Rice Cooker: 59
3 - Espresso Beans: 24.5
4 - Notebook: 3.25
bash · try it yourself
jq '.products[1].brand // "unknown"' products.json
"unknown"

Transforming

jq can also change data — the output is a modified copy; the file itself is untouched:

bash · try it yourself
jq -c '.products[0] | .price = 5 | del(.tags)' products.json
{"id":1,"name":"Green Tea","category":"drinks","price":5,"stock":120}
bash · try it yourself
jq -c '.products | map({(.name): .stock}) | add' products.json
{"Green Tea":120,"Rice Cooker":8,"Espresso Beans":0,"Notebook":300}

jq as a validator

jq refuses invalid JSON with a non-zero exit code, which makes it handy in scripts:

bash · try it yourself
echo '{"a": 1,}' | jq .
parse error: Expected another key-value pair at line 1, column 9

The same queries in JavaScript

Every jq filter has a JavaScript equivalent. Comparing them helps you read both:

js · try it yourself
const data = {
  products: [
    { id: 1, name: "Green Tea", category: "drinks", price: 4.5, stock: 120 },
    { id: 2, name: "Rice Cooker", category: "kitchen", price: 59, stock: 8 },
    { id: 3, name: "Espresso Beans", category: "drinks", price: 24.5, stock: 0 },
    { id: 4, name: "Notebook", category: "office", price: 3.25, stock: 300 },
  ],
};

// jq '.products[] | select(.price > 20) | .name'
data.products.filter((p) => p.price > 20).forEach((p) => console.log(p.name));

// jq '.products | map(.price) | add / length'
const prices = data.products.map((p) => p.price);
console.log(prices.reduce((a, b) => a + b, 0) / prices.length);

// jq -c '.products[] | {id, stock}'
for (const { id, stock } of data.products) console.log(JSON.stringify({ id, stock }));
Rice Cooker
Espresso Beans
22.8125
{"id":1,"stock":120}
{"id":2,"stock":8}
{"id":3,"stock":0}
{"id":4,"stock":300}

Cheat sheet

Filter Meaning
. whole input
.a.b nested key
.a[2], .a[-1] array item (from the end with negatives)
.a[] each item
f | g pipe results of f into g
[f] collect results into an array
{a, b} build an object
select(cond) keep matching results
map(f) apply f to every array item
x // y y if x is null/false/missing
-r, -c raw strings, compact output

Test yourself

What does jq '.products[]' output?

  1. The products array as one value
  2. Each product as a separate result
  3. Only the first product
  4. The number of products

Which jq option prints strings without quotes?

  1. -c
  2. -s
  3. -r
  4. -q

What does select(.stock == 0) do?

  1. Sets stock to 0
  2. Keeps only inputs whose stock is 0
  3. Counts items with stock 0
  4. Deletes the stock key