# jq for Apify Datasets - Transform, Filter & Reshape JSON (`northbell/jq-transform`) Actor

Real jq 1.8 over any Apify dataset, inline JSON or a JSON / JSON-lines link. Add it as an Integration and every scraper run comes out filtered and reshaped, with only-new dedupe across runs. Get dataset items, CSV or JSON.

- **URL**: https://apify.com/northbell/jq-transform.md
- **Developed by:** [Northbell](https://apify.com/northbell) (community)
- **Categories:** Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.08 / 1,000 items

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## jq for Apify Datasets - Transform, Filter & Reshape JSON

**Run a real jq program over your scraped data.** Give it a dataset (or inline JSON, or a link to a JSON file), write a jq program, and get the results back as dataset items, and optionally as a CSV or JSON file. It is built to run right after a scraper: filter rows, rename and flatten fields, turn text into numbers, dedupe, group and count, and skip items you already have.

The engine is jq 1.8 itself (compiled to WebAssembly), so every jq program you know from the command line or [jqplay](https://jqplay.org) works the same here.

**Try it now — the input is already filled in.** Press **Start**. It runs `select(.price != null) | {title, price: (.price|tonumber), url}` over 4 example products, one of which has no price. In our own local run with this input: **4 items in, 3 items out, about 2 seconds** from start to finish (the jq work itself took 0.2 seconds). Cost: 3 output items = **$0.0003** (plus $0.00005 for the run start).

| Event | Price | When |
| --- | --- | --- |
| `item-out` | $0.0001 | per output item written to the dataset ($0.10 per 1,000) |
| `apify-actor-start` | $0.00005 | once per run |

- You pay only for items that are written. Items dropped by your program, results skipped by "Only new items" and items that fail with a jq error are free.
- Set "Maximum total charge" on the run as your cap. The Actor checks the limit before it writes each batch and stops cleanly when the next results do not fit.

### Run it after your scraper

Use it as an Integration so every scraper run is cleaned up automatically:

1. In Apify Console, open your scraper and go to **Integrations**.
2. Add **Run Actor** (on "Run succeeded") and pick this Actor.
3. Use an input like this:

```json
{
  "datasetId": "{{resource.defaultDatasetId}}",
  "program": "select(.price != null) | {title, price: (.price|tonumber), url}",
  "mode": "perItem",
  "outputFile": "csv"
}
```

Each run of the scraper hands its dataset over; the cleaned items appear in this Actor's own dataset, and the CSV is in its key-value store. In per-item mode the dataset is read 1,000 items at a time, so a dataset with hundreds of thousands of items does not have to fit in memory.

### Run it on a schedule with only new items

Turn on `onlyNew` and schedule the run. The Actor keeps a list of the keys it has already output in a key-value store named `jq-transform-seen` in your account. `keyPath` is a jq expression for the key of one **output** item (`.url` by default; `.id`, or `(.shop + "/" + .sku)` work too). On the next run, results whose key is in the list are skipped and not charged.

```json
{
  "datasetId": "{{resource.defaultDatasetId}}",
  "program": "{id, title, price: (.price|tonumber)}",
  "onlyNew": true,
  "keyPath": ".id"
}
```

- The list belongs to one program plus key expression. If you change either, you start with an empty list (so two different jobs in one account never hide each other's items).
- A result without a key (the expression gives `null` or fails) is always kept and never remembered.
- Keys are only marked as seen after their item is written to the dataset. Results cut off by a charge limit or a time limit are picked up by the next run.
- Duplicate keys inside one run are also skipped (the first one wins).
- The list holds up to 300,000 keys (the oldest are dropped). If the store cannot be opened, the run stops before charging anything.

### Input

| Field | Default | What it does |
| --- | --- | --- |
| `program` | the example above | the jq program |
| `mode` | `perItem` | `perItem` runs the program on each item (0, 1 or many results per item, streams through big datasets). `wholeArray` gives the program all items as one array (for `group_by`, `unique_by`, `sort_by`, totals); capped by `maxItems` |
| `json` | 4 example products | inline items (a JSON array) |
| `datasetId` | - | read items from this dataset |
| `sourceUrl` | - | a public link to a JSON array/object or a JSON-lines file (up to 200 MB). Private and local addresses are blocked |
| `onlyNew`, `keyPath` | off, `.url` | skip results whose key was output in an earlier run |
| `outputFile` | `none` | also store all results as one `csv` or `json` file in the run's key-value store |
| `maxItems` | 100000 | most input items read in a run (1 to 1,000,000) |

If you give more than one source, they are read in the order `json`, `datasetId`, `sourceUrl`, up to `maxItems` items in total.

How results become items:

- Each jq output value is one dataset item. A result that is not an object (a string, a number, an array, `null`) is stored as `{"value": ...}`.
- In `wholeArray` mode, a program that returns **one array** (like `unique_by(.url)` or `sort_by(.price)`) gives one item per element. Use `.[]` yourself if you prefer.
- Numbers keep their precision (jq 1.8 keeps big integers as written unless the program changes them).

### Output files

With `outputFile` set to `csv` or `json`, the results are also stored in the run's key-value store as `OUTPUT.csv` or `OUTPUT.json`. The link is written to the log and to the `OUTPUT` record, together with the run summary:

```json
{
  "itemsIn": 4,
  "itemsOut": 3,
  "errors": 0,
  "firstErrors": [],
  "skippedAlreadySeen": 0,
  "charged": { "item-out": 3 },
  "stopReason": null,
  "seconds": 0.3,
  "files": {}
}
```

CSV columns are the union of all fields in order of first appearance. Nested values (objects and arrays) are written as JSON text in the cell, and cells with commas, quotes or line breaks are quoted. The results are held in memory while the file is built.

### Errors you can read

- **A syntax error stops the run before anything is read or charged**, and shows jq's own message, for example:

  ```
  The jq program does not compile:
  error: syntax error, unexpected end of file, expecting '}' at <top-level>, line 1, column 33:
      {title, price: (.price|tonumber)
                                      ^
  Nothing was charged.
  ```

- **A runtime error in per-item mode** (for example `tonumber` on a text that is not a number) names the item and carries on with the others: `jq error at item index 2 (counting from 0): string ("abc") cannot be parsed as a number - item: {"price":"abc"}`. The first 20 are in the `OUTPUT` record, and the status says how many items failed. If every item fails, the run fails with the first message.

- **A runtime error in whole-array mode** fails the run (the program ran once, on everything).

- **A program that never ends** is cut off after 60 seconds per batch of items (300 seconds in whole-array mode) with the item range it was working on.

### Cookbook: 8 jq recipes for scraped data

Each recipe below is run by the Actor's test suite with the example shown.

**1. Flatten nested fields**

```
{id, name: .user.name, city: .user.address.city}
```

`{"id": 1, "user": {"name": "Ana", "address": {"city": "Lisbon", "zip": "1000"}}}` becomes `{"id": 1, "name": "Ana", "city": "Lisbon"}`.

**2. Rename fields**

```
{title: .name, url: .href, price: .cost}
```

`{"name": "Lamp", "href": "https://x.test/lamp", "cost": 20, "junk": true}` becomes `{"title": "Lamp", "url": "https://x.test/lamp", "price": 20}`. Fields you do not name are dropped.

**3. Dedupe by a key** (mode `wholeArray`)

```
unique_by(.url)
```

Three items where two share `url: "b"` give two items; the first of each key is kept (the result is sorted by the key).

**4. Filter by date** (mode `perItem`)

```
select(.date >= "2025-01-01")
```

ISO dates compare correctly as text, so this keeps `2025-01-01` and `2025-06-30T10:00:00Z` and drops `2024-12-31`. Items that do not match produce no output, which is how filtering works in jq.

**5. Split an array into rows**

```
{id, image: .images[]}
```

`{"id": 1, "images": ["a.jpg", "b.jpg"]}` becomes two items, `{"id": 1, "image": "a.jpg"}` and `{"id": 1, "image": "b.jpg"}`. An item with an empty list gives no rows.

**6. Pick fields**

```
pick(.title, .price)
```

`{"title": "T", "price": 5, "html": "<p>x</p>", "debug": {}}` becomes `{"title": "T", "price": 5}`. To drop a few fields and keep the rest, use `del(.html, .debug)`.

**7. String to number**

```
.price |= (gsub("[^0-9.]"; "") | tonumber)
```

`{"price": "$1,299.50"}` becomes `{"price": 1299.5}`. Add `select(.price != null) |` in front to skip items without a price, because `tonumber` on `null` is an error.

**8. Group and count** (mode `wholeArray`)

```
group_by(.category) | map({category: .[0].category, count: length})
```

Items with `category` shoes, socks, shoes, shoes give `{"category": "shoes", "count": 3}` and `{"category": "socks", "count": 1}`.

### Speed and size

Measured on our own machine (Windows, Node 24, not on the Apify platform), with 100,000 synthetic product items of about 350 bytes each (nested seller object, a tags list, 10% without a price):

| Run | Time | Peak memory |
| --- | --- | --- |
| per item: filter, `tonumber`, rename, join tags (100,000 in, 90,000 out) | 3.1 s | 108 MB |
| the same with a CSV file built at the end | 2.8 s | 262 MB |
| the same with "Only new items" on | 3.1 s | 287 MB |
| whole array: `group_by(.category)` and count | 3.0 s | 502 MB |
| whole array: `unique_by(.seller.name)` | 3.4 s | 534 MB |

These times are for the jq work with the results counted but not stored. The complete Actor run on the same data (reading a local dataset of 100,000 items, writing 90,000 result items) took 423 seconds and peaked at 353 MB, almost all of it Apify's local test storage writing one file per item; on the platform the dataset writes are batched, and we have not timed that part there. Whole-array mode needs about 4 to 5 MB of memory per 1,000 of these items on top of the base, so the default 1,024 MB covers roughly 100,000 items of this size; raise the Actor's memory for larger items.

### Limits

- The jq program runs inside this Actor only; it cannot read environment variables, files or the network (`import`, `include` and `$ENV` see nothing of the host).
- Per-item mode streams a dataset, but the output file (`outputFile`) and whole-array mode hold their data in memory. At the default 1,024 MB, keep those to about 100,000 small items; raise the Actor's memory for more.
- A link source is read into memory (up to 200 MB). Only public http(s) links are allowed.
- `import`/`include` of jq modules and `--arg` style variables are not available; put values in the program text.

### 日本語

Apify のデータセット(またはインライン JSON、JSON ファイルへのリンク)に対して、本物の jq(WebAssembly 版 jq 1.8)のプログラムを実行し、結果をデータセットの項目として返します。CSV / JSON ファイルの同時出力にも対応。スクレイパーの後にインテグレーションとして実行する使い方を想定しています(`datasetId` に `{{resource.defaultDatasetId}}`)。項目ごとの実行(大きなデータセットも少しずつ処理)と、配列全体を渡す実行(`group_by`・`unique_by` など)を選べます。「新しい項目のみ」を有効にすると、過去の実行で出力済みのキーを飛ばします。jq の構文エラーは課金前に止まり、実行時エラーは項目の番号付きで表示されます。料金は出力1件あたり $0.0001(1,000件で $0.10)、書き込めた分だけの課金です。

# Actor input Schema

## `program` (type: `string`):

The jq program. In per-item mode it runs on every item (`.` is the item) and may output nothing (the item is dropped), one result or many. In whole-array mode `.` is the array of all items. Each output value becomes one dataset item; a result that is not an object (a string, number, array or null) is stored as {"value": ...}.

## `mode` (type: `string`):

perItem runs the program on each item separately and streams through big datasets. wholeArray gives the program the full array (needed for group_by, unique_by, sort_by and totals); it holds all items in memory, capped by Max items. If the program returns a single array, each element becomes one item.

## `json` (type: `array`):

Items to process, right here: a JSON array (one item per element). Use it to try a program. Leave it empty when you read a dataset or a link.

## `datasetId` (type: `string`):

Read the items from this Apify dataset (for example the dataset of a scraper run). Read page by page, so a big dataset does not have to fit in memory in per-item mode. Use {{resource.defaultDatasetId}} when you connect this Actor as an integration after another Actor.

## `sourceUrl` (type: `string`):

A link to a JSON file (an array, or one object) or a JSON-lines file (one JSON value per line). Only public http(s) links; private and local addresses are blocked. The file is read into memory (up to 200 MB).

## `onlyNew` (type: `boolean`):

Skip results whose key was already output in an earlier run (kept in a key-value store named jq-transform-seen in your account, separately for each program + key expression). Use it for scheduled runs. Skipped results are free.

## `keyPath` (type: `string`):

A field name (id, url, shop.sku) or a jq expression that gives the key of one result, for example .url or .id or (.shop + "/" + .sku). It is run on the output items. A result without a key (null) is always kept.

## `outputFile` (type: `string`):

Besides the dataset, store all results as one file in the run's key-value store. CSV columns are the union of all fields; nested values are written as JSON text. The link is in the log and in the OUTPUT record. The results are held in memory for this.

## `maxItems` (type: `integer`):

Most input items read in one run (1 to 1,000,000).

## Actor input object example

```json
{
  "program": "select(.price != null) | {title, price: (.price|tonumber), url}",
  "mode": "perItem",
  "json": [
    {
      "title": "Trail running shoes",
      "price": "89.90",
      "url": "https://shop.example/p/1"
    },
    {
      "title": "Merino socks, 3 pack",
      "price": "24.00",
      "url": "https://shop.example/p/2"
    },
    {
      "title": "Headlamp 400 lumen",
      "price": null,
      "url": "https://shop.example/p/3"
    },
    {
      "title": "Water bottle 750 ml",
      "price": "12.50",
      "url": "https://shop.example/p/4"
    }
  ],
  "onlyNew": false,
  "keyPath": ".url",
  "outputFile": "none",
  "maxItems": 100000
}
```

# Actor output Schema

## `results` (type: `string`):

One dataset item per jq output.

## `summary` (type: `string`):

Items in and out, errors, charge, and links to the CSV / JSON file when you asked for one.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "program": "select(.price != null) | {title, price: (.price|tonumber), url}",
    "mode": "perItem",
    "json": [
        {
            "title": "Trail running shoes",
            "price": "89.90",
            "url": "https://shop.example/p/1"
        },
        {
            "title": "Merino socks, 3 pack",
            "price": "24.00",
            "url": "https://shop.example/p/2"
        },
        {
            "title": "Headlamp 400 lumen",
            "price": null,
            "url": "https://shop.example/p/3"
        },
        {
            "title": "Water bottle 750 ml",
            "price": "12.50",
            "url": "https://shop.example/p/4"
        }
    ],
    "keyPath": ".url"
};

// Run the Actor and wait for it to finish
const run = await client.actor("northbell/jq-transform").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "program": "select(.price != null) | {title, price: (.price|tonumber), url}",
    "mode": "perItem",
    "json": [
        {
            "title": "Trail running shoes",
            "price": "89.90",
            "url": "https://shop.example/p/1",
        },
        {
            "title": "Merino socks, 3 pack",
            "price": "24.00",
            "url": "https://shop.example/p/2",
        },
        {
            "title": "Headlamp 400 lumen",
            "price": None,
            "url": "https://shop.example/p/3",
        },
        {
            "title": "Water bottle 750 ml",
            "price": "12.50",
            "url": "https://shop.example/p/4",
        },
    ],
    "keyPath": ".url",
}

# Run the Actor and wait for it to finish
run = client.actor("northbell/jq-transform").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "program": "select(.price != null) | {title, price: (.price|tonumber), url}",
  "mode": "perItem",
  "json": [
    {
      "title": "Trail running shoes",
      "price": "89.90",
      "url": "https://shop.example/p/1"
    },
    {
      "title": "Merino socks, 3 pack",
      "price": "24.00",
      "url": "https://shop.example/p/2"
    },
    {
      "title": "Headlamp 400 lumen",
      "price": null,
      "url": "https://shop.example/p/3"
    },
    {
      "title": "Water bottle 750 ml",
      "price": "12.50",
      "url": "https://shop.example/p/4"
    }
  ],
  "keyPath": ".url"
}' |
apify call northbell/jq-transform --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,northbell/jq-transform"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/LjD3mYT3RfAVCgJQo/builds/SL7jAOA6xnjimLr5e/openapi.json
