# Merge, Deduplicate & Convert Datasets — CSV, JSON, Excel (`docflow-tools/merge-dedupe-transform-data`) Actor

Merge Apify datasets and CSV, JSON, JSONL or Excel files, remove duplicates (exact or fuzzy: case, accents, spaces), pick and rename fields, flatten nested JSON and export to CSV or Excel. Limited permissions: reads only the datasets you pick.

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

## Pricing

from $0.16 / 1,000 output rows

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

## Merge, Deduplicate & Convert Datasets — CSV, JSON, Excel

Combine **Apify datasets** and **CSV, JSON, JSONL or Excel (XLSX) files** into one clean table. The Actor removes
duplicate rows (exact or fuzzy: ignoring case, accents and extra spaces), keeps the first or last occurrence, picks,
reorders and renames fields, flattens nested JSON and can export the result as a CSV or Excel file. It runs with
**limited permissions**: it can read only the datasets you pick in the input, and nothing else in your account. You pay
per row delivered; removed duplicates are free.

### What you get

- **Dataset**: the merged rows. Each item is one of your rows, with your own field names (after picking, renaming and
  flattening).
- **Key-value store, `SUMMARY`**: run totals.
- **Key-value store, `OUTPUT`**: the CSV or XLSX file, only if you set *Also export a file*.

`SUMMARY` fields:

| Field | Description |
|---|---|
| `rowsRead` | Rows read from all sources |
| `duplicatesRemoved` | Rows dropped as duplicates |
| `rowsOutput` | Rows after deduplication and transformation |
| `sources` | Number of datasets plus file URLs given |
| `errors` | `[{ "source", "error" }]` for each dataset or file that could not be read |
| `stoppedAtSpendingLimit` | `true` only if the run stopped at your maximum cost per run |

If no rows are left, the dataset gets a single item with `"status": "no_rows"` and the same totals (not charged).

### Use cases

- **Merge scraper runs**: combine the datasets of several runs of any Actor and drop the items you already had.
- **Clean a lead list or product feed you own**: remove repeated rows by an ID, SKU, email or URL column.
- **Fuzzy matching**: treat `" José García "` and `"jose garcia"` as the same value.
- **Convert formats**: JSON or JSONL to CSV or Excel, Excel to JSON, nested JSON to flat columns.
- **Prepare data for a spreadsheet or BI tool**: keep only the columns you need, in your order, with your names.

### How to use

1. In *Apify datasets*, pick one or more of your datasets (the picker grants read-only access to those only), and/or
   add file links in *File URLs*.
2. Keep *Remove duplicates* on and list the *Fields that define a duplicate* (empty = compare the whole row).
3. Optional: turn on *Fuzzy match*, choose *Keep* = first or last, list *Fields to keep*, set *Rename fields*, turn on
   *Flatten nested JSON*.
4. Optional: set *Also export a file* to CSV or Excel.
5. Click **Start**. Rows appear in the *Output* tab; the file and the summary are in the run's key-value store.

Input example:

```json
{
  "datasetIds": ["YOUR_DATASET_ID"],
  "fileUrls": ["https://raw.githubusercontent.com/datasets/currency-codes/main/data/codes-all.csv"],
  "deduplicate": true,
  "dedupeFields": ["AlphabeticCode"],
  "fuzzyMatch": false,
  "keep": "first",
  "fields": ["AlphabeticCode", "Currency", "Entity"],
  "rename": { "AlphabeticCode": "code" },
  "flatten": false,
  "exportFormat": "csv"
}
```

### Output example

Running the example input with only the currency-codes CSV (no dataset), the first dataset items are:

```json
[
  { "code": "AFN", "Currency": "Afghani", "Entity": "AFGHANISTAN" },
  { "code": "EUR", "Currency": "Euro", "Entity": "ÅLAND ISLANDS" }
]
```

And `SUMMARY` for that run (449 rows in the file, 308 distinct currency codes):

```json
{ "rowsRead": 449, "duplicatesRemoved": 141, "rowsOutput": 308, "sources": 1, "errors": [] }
```

### How it works, step by step

1. **Read** every picked dataset (in order), then every file URL (in order).
2. **Deduplicate** across all sources together, using the fields you listed or the whole row.
3. **Transform** each row in this order: flatten, pick fields, rename, trim spaces at the start and end of text values.
4. **Output** the rows to the dataset, then write `OUTPUT` (if requested) and `SUMMARY`.

Because picking happens after flattening and before renaming, *Fields to keep* uses the flattened names (`a.b`) and
the original names (before rename).

### Pricing

> **Prices by Apify discount tier:** the prices below are for the Bronze tier. **Free plan: 50 % off.** Silver: 10 % off. Gold and higher: 20 % off. Apify applies the right price automatically.

Pay per event, in USD:

| Event | Price | When it is charged |
|---|---|---|
| Actor start | $0.00005 | Charged by Apify when a run starts, per GB of run memory (default memory: 1 GB) |
| `row-output` | $0.0002 | Per row written to the output dataset ($0.20 per 1,000 rows) |

Not charged: rows removed as duplicates, sources that fail to load, the `no_rows` item, the `SUMMARY` record and the
exported file.

Worked examples (1 GB run, start = $0.00005):

- Two copies of a 449-row CSV: 898 rows read, 590 duplicates removed, 308 rows output. 308 × $0.0002 = $0.0616, plus
  start = **$0.06165**.
- Five scraper datasets, 50,000 rows read, 12,000 duplicates: 38,000 × $0.0002 = $7.60, plus start = **$7.60005**.
- Convert a 10,000-row JSON file to Excel with no duplicates: 10,000 × $0.0002 = $2.00, plus start = **$2.00005**.

Set Apify's *maximum cost per run* to cap the spend: output stops when the limit is reached and `SUMMARY` shows
`"stoppedAtSpendingLimit": true`.

### Use it from code, AI agents and integrations

Apify API, run and get the rows in one call (waits up to 5 minutes; use the regular run endpoint for big jobs):

```bash
curl -X POST "https://api.apify.com/v2/acts/docflow-tools~merge-dedupe-transform-data/run-sync-get-dataset-items?token=YOUR_APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"fileUrls": ["https://example.com/leads-a.csv", "https://example.com/leads-b.json"], "dedupeFields": ["email"], "fuzzyMatch": true}'
```

Python with `apify-client`:

```python
from apify_client import ApifyClient

client = ApifyClient("YOUR_APIFY_TOKEN")
run = client.actor("docflow-tools/merge-dedupe-transform-data").call(run_input={
    "datasetIds": ["DATASET_ID_1", "DATASET_ID_2"],
    "dedupeFields": ["url"],
    "keep": "last",
    "exportFormat": "xlsx",
})
rows = list(client.dataset(run["defaultDatasetId"]).iterate_items())
summary = client.key_value_store(run["defaultKeyValueStoreId"]).get_record("SUMMARY")["value"]
print(len(rows), summary)
```

- **AI agents**: the Actor can be found and called by AI agents through the Apify MCP server at https://mcp.apify.com.
- **No-code**: use it from Make, Zapier or n8n through Apify's integrations, or chain it after another Actor with an
  Apify webhook or schedule.

### Limits and notes

- **Up to 1,000,000 rows per run**, held in memory. Rows beyond the limit are not read.
- **Files up to 200 MB each**, `http` or `https` only, 180-second timeout, redirects followed.
- **Format detection is by content**: XLSX by its file signature; JSON if the whole file parses as JSON; JSONL if it
  starts with `{` and is not a single JSON document (or the name ends in `.jsonl`/`.ndjson`); anything else is CSV.
- **CSV**: separator detected among comma, semicolon, tab and `|`; UTF-8 (with or without BOM), falling back to
  Windows-1252 for files saved by Excel on Windows. All CSV values are read as text.
- **Excel**: only the first sheet; the first row is the header (empty header cells become `column_1`, `column_2`...);
  fully empty rows are skipped; formulas give their saved values.
- **JSON**: an array of objects; if the top level is an object, its first list is used (or the object itself as one
  row). Items that are not objects are skipped.
- **Exact matching compares values as they are**, before spaces are trimmed: `"abc "` and `"abc"` are different
  unless *Fuzzy match* is on. Numbers and text with the same characters match (`1` and `"1"`).
- A missing or empty dedupe field counts as an empty value, so rows that all lack that field are treated as
  duplicates of each other.
- *Keep = last* keeps the latest copy of a row in the position where it first appeared.
- *Fields to keep* outputs listed fields even if a row lacks them (as `null`).
- **Flatten** joins nested keys with a dot; lists are stored as JSON text. In the CSV and Excel export, any remaining
  nested value is also written as JSON text. The CSV is UTF-8 with BOM (opens correctly in Excel); the Excel sheet is
  named `data`.
- A dataset or file that fails to load does not stop the run: it is listed in `SUMMARY.errors`.

### FAQ

**Why does it need me to pick datasets instead of typing an ID?**
The picker gives the Actor read access to exactly those datasets for this run. That is what lets it run with limited
permissions instead of full access to your account.

**Can I deduplicate by several columns?**
Yes. List them all in *Fields that define a duplicate*; rows are duplicates only when every listed field matches.

**Does fuzzy match find similar spellings like "Jon" and "John"?**
No. Fuzzy match ignores case, accents and repeated or surrounding spaces. It does not compare spelling similarity.

**Can I just convert a file without removing duplicates?**
Yes. Turn off *Remove duplicates* and set *Also export a file*.

**Where is my CSV or Excel file?**
In the run's default key-value store, under the key `OUTPUT` (also linked in the run's *Output* tab).

### Related tools

- [Document to Markdown for RAG](https://apify.com/docflow-tools/document-to-markdown-rag) — PDF, DOCX, XLSX, PPTX and HTML to clean Markdown with RAG chunks.
- [Feed Reader — only new items](https://apify.com/docflow-tools/feed-reader-only-new) — RSS, Atom and JSON Feed, returning only items you haven't seen.
- [PageSpeed Bulk Regression Monitor](https://apify.com/docflow-tools/pagespeed-bulk-regression-monitor) — PageSpeed Insights and Core Web Vitals for many URLs, flags regressions.
- [Image OCR](https://apify.com/docflow-tools/image-ocr-own-engine) — extract text from images with an own OCR engine.
- [Audio & Video Transcriber](https://apify.com/docflow-tools/audio-transcriber-whisper-local) — Whisper transcripts, SRT and VTT, billed per minute.
- [Website Screenshot & Visual Change Monitor](https://apify.com/docflow-tools/website-screenshot-monitor) — bulk screenshots and visual change detection.
- [Bulk Image Converter & Compressor](https://apify.com/docflow-tools/bulk-image-converter-compressor) — convert to WebP, AVIF, JPEG or PNG with a target size.
- [Sitemap URL Extractor](https://apify.com/docflow-tools/sitemap-url-extractor-reliable) — every URL of a website from its sitemaps.
- [SEO Audit Crawler](https://apify.com/docflow-tools/seo-audit-crawler-cheap) — on-page SEO score and issues per page.
- [Website to Markdown & llms.txt](https://apify.com/docflow-tools/website-to-markdown-llms-txt) — websites to clean Markdown and llms.txt for LLMs.

# Actor input Schema

## `datasetIds` (type: `array`):

Pick one or more of your Apify datasets to merge. The Actor gets read-only access to the ones you pick.

## `fileUrls` (type: `array`):

CSV, JSON, JSONL or Excel (XLSX) file links (http or https, up to 200 MB each).

## `deduplicate` (type: `boolean`):

Remove repeated rows.

## `dedupeFields` (type: `array`):

Rows with the same values in these fields are duplicates. Empty = compare the whole row.

## `fuzzyMatch` (type: `boolean`):

Ignore case, accents and extra spaces when comparing (' José ' equals 'jose').

## `keep` (type: `string`):

Which duplicate to keep.

## `fields` (type: `array`):

Output only these fields, in this order. Empty = all fields.

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

Map of old name to new name, e.g. {"AlphabeticCode": "code"}.

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

Turn {"a": {"b": 1}} into a column named a.b (lists become JSON text).

## `exportFormat` (type: `string`):

Save the result also as a CSV or Excel file (key OUTPUT in the run's key-value store).

## Actor input object example

```json
{
  "fileUrls": [
    "https://raw.githubusercontent.com/datasets/currency-codes/main/data/codes-all.csv"
  ],
  "deduplicate": true,
  "dedupeFields": [
    "AlphabeticCode"
  ],
  "fuzzyMatch": false,
  "keep": "first",
  "flatten": false,
  "exportFormat": "none"
}
```

# Actor output Schema

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

No description

## `file` (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 = {
    "fileUrls": [
        "https://raw.githubusercontent.com/datasets/currency-codes/main/data/codes-all.csv"
    ],
    "dedupeFields": [
        "AlphabeticCode"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("docflow-tools/merge-dedupe-transform-data").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 = {
    "fileUrls": ["https://raw.githubusercontent.com/datasets/currency-codes/main/data/codes-all.csv"],
    "dedupeFields": ["AlphabeticCode"],
}

# Run the Actor and wait for it to finish
run = client.actor("docflow-tools/merge-dedupe-transform-data").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 '{
  "fileUrls": [
    "https://raw.githubusercontent.com/datasets/currency-codes/main/data/codes-all.csv"
  ],
  "dedupeFields": [
    "AlphabeticCode"
  ]
}' |
apify call docflow-tools/merge-dedupe-transform-data --silent --output-dataset

```

## MCP server setup

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

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/JsvUU510kNJE3DUgT/builds/cj0fAdu5iS7orWMKf/openapi.json
