# Dataset Transformer: Filter, Dedupe, JSON to CSV (`gunpark/dataset-transformer`) Actor

Clean datasets and JSON/CSV/JSONL with declarative filtering, deduplication, casting and CSV/JSONL exports.

- **URL**: https://apify.com/gunpark/dataset-transformer.md
- **Developed by:** [Alejandro Rodriguez](https://apify.com/gunpark) (community)
- **Categories:** Developer tools, Automation, Integrations
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 80.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.08 / 1,000 row inspecteds

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

## Dataset Transformer: Filter, Dedupe, JSON to CSV

Clean an Apify dataset, inline JSON, or a public CSV/JSONL file using declarative rules. Export the result as a fresh dataset plus CSV and JSONL downloads. No arbitrary JavaScript, AI calls, enrichment or external processing service.

Use this Actor to clean other Actors' output, deduplicate product inventories, select fields for a CRM import, cast quantities before analysis, or prepare compact records for AI agents and MCP workflows. An agent can submit a JSON configuration and read `OUTPUT_SUMMARY` before retrieving the dataset or export links.

### Quick start

```json
{
  "inlineJson": [{"sku":"A","qty":"2"},{"sku":"A","qty":"2"},{"sku":"B","qty":"3"}],
  "cast": {"qty":"integer"},
  "dedupeBy": ["sku"]
}
```

Result: `[{"sku":"A","qty":2},{"sku":"B","qty":3}]`. This is the self-contained daily demo and the fallback for an empty input object. Three inspected rows and one valid run cost **$0.0013** at the configured event prices.

### Inputs

Supply exactly **one** source. Clear the inline JSON editor when switching to a dataset or URL. Omitted rules use the defaults below; the demo's cast and dedupe rules are editor prefills, not hidden rules for other sources.

| Field | Type / default | Meaning |
|---|---|---|
| `datasetId` | string | Existing 17-character Apify dataset ID, read with the current run's token. No creator token is used. |
| `inlineJson` | object array | JSON records; an empty array is a valid source. |
| `csvUrl` | HTTP(S) URL | Public UTF-8 comma-separated CSV with unique, nonempty headers. |
| `jsonlUrl` | HTTP(S) URL | Public UTF-8 JSON objects, one per line; blank lines ignored. |
| `flatten` | boolean / `false` | Recursively flatten objects; arrays and empty objects remain values. |
| `separator` | string / `.` | Flatten separator, 1–8 characters. |
| `select` | string array / `[]` | Keep these fields, in this order; empty keeps all. Dot paths supported. |
| `rename` | object / `{}` | Simultaneous exact field-name replacements, e.g. `{"old":"new"}`. |
| `cast` | object / `{}` | Field → `integer`, `number`, `boolean`, `string`, or `date`. |
| `filters` | array / `[]` | AND of `{field, op, value}` rules. |
| `dedupeBy` | string array / `[]` | Keep first occurrence of each transformed key tuple. |
| `sortBy` | array / `[]` | Stable sorting using `{field, desc:false}` rules in priority order. |
| `limit` | integer / `100000` | Maximum output rows, applied last; zero produces empty exports. |

Order: **flatten → select → rename → cast → filter → deduplicate → sort → limit**. Filters, dedupe and sort reference the resulting field names. Literal dotted keys take precedence over nested dot paths. Select and cast produce literal keys for dot paths; they do not rebuild nested objects. Rename changes exact keys. Collisions in flatten/rename are invalid and rejected before billing. Missing selected fields become null.

Supported operators: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `contains`, `notContains`, `regex`, `isEmpty`, `notEmpty`. Empty means missing, null, empty string or empty array. Equality is type-sensitive and compares objects structurally. Ordered comparisons require matching string/number types. Text operations are case-sensitive. Regex uses JavaScript Unicode syntax without flags; syntax is checked before billing and execution runs in an isolated worker with a 2-second deadline per 1,000 values. Pathological expressions can fail a valid, already billed run; simplify them and retry.

Invalid cast values become null. Integers must be safe whole numbers; numbers must be finite. Boolean accepts true/false, 1/0 and their lowercase string equivalents. Dates accept ISO calendar dates or timezone-qualified ISO timestamps and return UTC ISO strings. Objects cast to string use JSON. Null/missing values stay null. CSV inputs have string values until cast. Dedupe keys distinguish missing from null and ignore object key order. Numeric sort is numeric when both values are numbers, otherwise text order; null/missing sort last ascending and first descending. Ties retain input order.

### More examples

Clean another Actor's dataset (replace the placeholder with your dataset ID):

```json
{
  "datasetId": "YOUR_DATASET_ID__1",
  "flatten": true,
  "select": ["product.sku", "product.price", "category"],
  "rename": {"product.sku":"sku", "product.price":"price"},
  "cast": {"price":"number"},
  "filters": [{"field":"price", "op":"gt", "value":0}],
  "dedupeBy": ["sku"],
  "sortBy": [{"field":"price", "desc":true}],
  "limit": 100
}
```

For a file, use `{"csvUrl":"https://example.com/your-export.csv","cast":{"qty":"integer"}}` or `{"jsonlUrl":"https://example.com/your-export.jsonl"}` with an actual public file you are authorized to process. These URLs are placeholders, not demo fixtures.

### Outputs

- Default dataset: transformed rows, without extra billing per output row.
- `output.csv`: RFC 4180 escaping, CRLF endings, union of output columns. Objects/arrays are JSON cells. Formula-like cells and headers starting with `=`, `+`, `-`, `@` (including after whitespace) receive a leading apostrophe. This also changes negative numeric cells into spreadsheet-safe text. JSONL/dataset values retain their original types.
- `output.jsonl`: one JSON object per line, UTF-8.
- `OUTPUT_SUMMARY` and `STATE`: `read`, `inspected`, `filtered`, `duplicates`, `limited`, `output`, charged event counts, charge-limit status, estimated maximum event cost, and public `csvUrl`/`jsonlUrl` links after success. `read` counts validated source rows; `inspected` counts the paid prefix processed. `inspected = filtered + duplicates + limited + output` after successful completion. Counts before failure/abort may be partial.
- `OUTPUT_PROVENANCE`: output row → original source row mapping (both 1-based). Source row numbers for CSV exclude the header; JSONL numbers count nonblank records. Dedupe preserves the first matching source row.

Empty output produces empty CSV/JSONL files. Export links are public KVS links; use appropriate retention settings and share them only with intended recipients. Store retention/access settings may restrict availability. Abort saves partial summaries; resumable/restart processing is not supported and a new run starts over.

### Pricing

Configured pay-per-event prices: **$0.001 per valid run** plus **$0.0001 per input row inspected**. At 1,000 input rows: `$0.001 + 1,000 × $0.0001 = $0.101`. Filtered rows, duplicates and rows beyond the output limit count as inspected. Exports are included. No output-row charge.

The complete source and configuration are validated before the run fee. Invalid rules, malformed files, unsafe/inaccessible URLs and inputs exceeding limits cause no Actor event charges. Valid empty input arrays incur the run fee. Failures after validation can retain charges for work already paid. Platform usage/storage charges may still apply according to your Apify plan.

The run fee is charged once, followed by row batches of at most 1,000. Each batch is capped to the SDK's remaining event capacity before charging. Only the successfully paid prefix is transformed. A charge-limit result stops further batches and exports the already paid rows. Set the run's maximum total charge in Apify to bound event spending. `estimatedMaxChargeUsd` in the summary shows the configured-price upper bound; before execution you can calculate the same formula from your input row count.

### Limits and source access

Maximum 100,000 input rows and 10 MiB per source (remote files also have a 10 MiB download cap; decoded JSON rows must fit 10 MiB). JSON depth is limited to 32; at most 100 entries per rule collection/map, 256 characters per field path, 512 characters per regex and 1,000 projected output columns. Structural output projection is limited to 20 MiB, and a conservative preflight CSV size estimate must fit 32 MiB. All rows are held in memory for sorting and dedupe; no streaming or multi-dataset merge is provided. Files must be UTF-8; BOM, LF and CRLF are supported. CSV has no delimiter inference, comments or automatic type inference. Uneven fields, duplicate headers and malformed quoting fail validation.

Downloads allow only public HTTP(S) destinations on ports 80/443, no embedded credentials, with DNS checks on the actual connection and every redirect, at most five redirects, a 30-second total download deadline and no compressed HTTP responses. Private, loopback, link-local, reserved and IPv4-mapped private addresses are blocked. Files requiring login are unsupported. Dataset reads use the SDK API client initialized from the current run environment/token and never create a dataset when the source is missing.

### Legal and development

Process only data you own or have permission to use. You are responsible for source terms, copyright, privacy, retention and lawful downstream use. This utility does not grant rights to scraped data, anonymize records or guarantee spreadsheet safety in every application. No third-party affiliation is implied.

Node 24+, ESM, Apify SDK 3. Direct runtime packages: Apify SDK (Apache-2.0) and ipaddr.js (MIT); Actor code ISC. Vite is overridden to 7.3.8 to avoid the MPL-licensed CSS tooling in Vite 8. See `VERIFICATION.md` for test/install evidence and license-audit scope. The layout derives from `actors/template-cheerio`; no direct Crawlee crawler dependency is retained (the Apify SDK itself uses Crawlee core).

```sh
npm ci
npm test
npm start
```

An empty local input runs the demo. No publication or pricing mutation is performed by this project. Before publication the owner must configure custom events `run` ($0.001) and `row-inspected` ($0.0001), with synthetic start/dataset-item charges disabled, and verify platform billing. Cloud runs require PPE; local non-PPE runs simulate processing without charges.

### More tools from the same author

- [PDF to Markdown & Text Extractor](https://apify.com/gunpark/pdf-to-markdown-extractor) – PDF URLs → Markdown/text/tables for RAG, flat $0.003 per PDF.
- [Bulk Image OCR](https://apify.com/gunpark/bulk-image-ocr) – image URLs → text (English & Spanish), $0.003 per image with text.
- [Bulk Image Converter & Compressor](https://apify.com/gunpark/image-converter-compressor) – PNG/JPEG → WebP/AVIF, resize, strip metadata.
- [Bulk PageSpeed Insights & Core Web Vitals Audit](https://apify.com/gunpark/bulk-pagespeed-audit) – Lighthouse scores + real-user Core Web Vitals for many URLs or a sitemap.

# Actor input Schema

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

Read an existing dataset using the current run token. Supply exactly one input source.

## `inlineJson` (type: `array`):

Array of objects. Clear this field when using a dataset or URL.

## `csvUrl` (type: `string`):

UTF-8 CSV with unique headers, comma delimiter; 10 MiB maximum.

## `jsonlUrl` (type: `string`):

UTF-8 newline-delimited JSON objects; 10 MiB maximum.

## `select` (type: `array`):

Dot paths; empty keeps every field. Runs after flattening.

## `rename` (type: `object`):

Map exact output field names to new names. Collisions are rejected.

## `flatten` (type: `boolean`):

Arrays remain intact. Conflicting keys are rejected.

## `separator` (type: `string`):

1 to 8 characters; default dot.

## `cast` (type: `object`):

Map fields to integer, number, boolean, string or date. Invalid values become null.

## `filters` (type: `array`):

Objects with field, op and value. Apply to transformed rows.

## `dedupeBy` (type: `array`):

Keep the first transformed matching row for each key tuple.

## `sortBy` (type: `array`):

Objects with field and optional desc boolean. Stable multi-field sorting.

## `limit` (type: `integer`):

Applied last; all paid input rows are inspected regardless of output limit.

## Actor input object example

```json
{
  "inlineJson": [
    {
      "sku": "A",
      "qty": "2"
    },
    {
      "sku": "A",
      "qty": "2"
    },
    {
      "sku": "B",
      "qty": "3"
    }
  ],
  "select": [],
  "rename": {},
  "flatten": false,
  "separator": ".",
  "cast": {
    "qty": "integer"
  },
  "filters": [],
  "dedupeBy": [
    "sku"
  ],
  "sortBy": [],
  "limit": 100000
}
```

# Actor output Schema

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

No description

## `csv` (type: `string`):

No description

## `jsonl` (type: `string`):

No description

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

No description

# 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 = {
    "inlineJson": [
        {
            "sku": "A",
            "qty": "2"
        },
        {
            "sku": "A",
            "qty": "2"
        },
        {
            "sku": "B",
            "qty": "3"
        }
    ],
    "cast": {
        "qty": "integer"
    },
    "dedupeBy": [
        "sku"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("gunpark/dataset-transformer").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 = {
    "inlineJson": [
        {
            "sku": "A",
            "qty": "2",
        },
        {
            "sku": "A",
            "qty": "2",
        },
        {
            "sku": "B",
            "qty": "3",
        },
    ],
    "cast": { "qty": "integer" },
    "dedupeBy": ["sku"],
}

# Run the Actor and wait for it to finish
run = client.actor("gunpark/dataset-transformer").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 '{
  "inlineJson": [
    {
      "sku": "A",
      "qty": "2"
    },
    {
      "sku": "A",
      "qty": "2"
    },
    {
      "sku": "B",
      "qty": "3"
    }
  ],
  "cast": {
    "qty": "integer"
  },
  "dedupeBy": [
    "sku"
  ]
}' |
apify call gunpark/dataset-transformer --silent --output-dataset

```

## MCP server setup

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

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/1V09GFvpxrq6DGXcN/builds/1gmCQLttwkiuDdHYh/openapi.json
