# Data Formatter & Converter: CSV, Excel, JSON, NDJSON, XML, YAML (`forlab/csv-json-schema-formatter`) Actor

Convert CSV, Excel, JSON, NDJSON, XML, YAML or HTML tables into JSON, CSV, Excel, SQL, Markdown or HTML. Merge up to 10 files, dedupe, filter, sort, flatten nested JSON, repair broken JSON, auto-detect delimiters and encodings, and validate rows against your example. Pay per valid row.

- **URL**: https://apify.com/forlab/csv-json-schema-formatter.md
- **Developed by:** [ForLab Digital](https://apify.com/forlab) (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.10 / 1,000 valid rows

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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

## Data Formatter & Converter: CSV, Excel, JSON, NDJSON, XML, YAML

Feed it messy rows — CSV, TSV, Excel (`.xlsx`), JSON, NDJSON/JSONL, XML, YAML or an HTML table, pasted, uploaded, from a file URL or from another Apify run's dataset — and say the output you want once, as a plain example object. Columns are matched to fields by name, every value is cleaned and validated, and you get back only the rows that pass, in your exact shape: before, a customer's chaotic export; after, a clean, typed, validated table (JSON, CSV, Excel and more).

- **Clean customer uploads:** a lead CSV with `Company Name;E-Mail` headers and broken rows becomes a validated lead list with exactly the columns you picked.
- **Reshape scraper output:** pass the scraper run's `datasetId` and get its records in your schema — no download, no code.
- **Normalize lead lists:** merge up to 10 files or datasets, drop duplicates, rename and reorder columns, parse dates, currencies and case styles.

### Quick start

One input works everywhere — paste it into the Console's **Input** (JSON view) and Start, or POST it to the API:

```json
{
  "text": "Company Name,Web Site,E-Mail\nOrnek Ltd,ornek.example,bilgi@ornek.example\nAcme Inc,acme.example,gecersiz-email\n",
  "targetExample": {"company_name": "Ornek Ltd", "website": "https://ornek.example", "email": "bilgi@ornek.example"}
}
```

Both rows are matched by column name; the first passes, the second fails the email check — so only the first is returned and charged:

```json
[
  {"company_name": "Ornek Ltd", "website": "https://ornek.example", "email": "bilgi@ornek.example"}
]
```

From the API (`run-sync-get-dataset-items` waits for the run and returns the dataset items):

```sh
curl -X POST "https://api.apify.com/v2/acts/forlab~csv-json-schema-formatter/run-sync-get-dataset-items?token=$APIFY_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"text": "Company Name,Web Site,E-Mail\nOrnek Ltd,ornek.example,bilgi@ornek.example\nAcme Inc,acme.example,gecersiz-email\n", "targetExample": {"company_name": "Ornek Ltd", "website": "https://ornek.example", "email": "bilgi@ornek.example"}}'
```

**Free plan:** `useAi` is on by default, but AI mapping runs only for paying Apify users. On the free plan, a column whose name doesn't match any target field ends the run `needs_mapping` — rename the column or add a `formatSpec` mapping rule. `OUTPUT.unmapped_targets` names the exact target fields that had no column.

### Reading row errors from the OUTPUT record

The run's `OUTPUT` record holds the summary: `status`, row counts, `removed` (`{filtered, duplicates}` when filter/dedupe dropped rows), a per-row report with each failed row's issues, `added_mapping` (the column→field rules the run used; paste them into **Format spec** to pin the mapping for later files), `dataset_items`, and whether AI ran (`ai`) or why not (`ai_off_reason`). In the Console it is the run's **Output** tab; over the API:

```sh
curl -s "https://api.apify.com/v2/actor-runs/$RUN_ID?token=$APIFY_TOKEN"                      # run details, with defaultKeyValueStoreId
curl -s "https://api.apify.com/v2/key-value-stores/$STORE_ID/records/OUTPUT?token=$APIFY_TOKEN"
```

For the quick start above, `OUTPUT.status` is `completed_with_errors` (`$0.001` run start, one charged row), and the failed row is named in the report:

```json
{"status": "completed_with_errors",
 "summary": {"received": 2, "processed": 2, "successful": 1, "failed": 1, "unprocessed": 0},
 "report": {"rows": [{"row_index": 1, "issues": [{"code": "SCHEMA_VALIDATION_FAILED", "path": ["email"], "keyword": "format"}]}]},
 "added_mapping": [
   {"from": {"column_id": "col_1"}, "to": "/company_name", "steps": [{"op": "trim"}]},
   {"from": {"column_id": "col_2"}, "to": "/website", "steps": [{"op": "trim"}, {"op": "normalize_url", "default_scheme": "https"}]},
   {"from": {"column_id": "col_3"}, "to": "/email", "steps": [{"op": "trim"}]}
 ],
 "dataset_items": 1}
```

(Trimmed — the record also carries the passing row's report, request id, detected delimiter and AI info. Rows download as JSON from the dataset, or as `results.csv` / `results.xlsx` from the run's output links, keeping your column order.)

A `needs_mapping` or `failed` run exits non-zero, so a sync call answers HTTP 400 with `{"error": {"type": "run-failed", "message": "Actor run did not succeed (run ID: …, status: FAILED)."}}` instead of rows. Take the run ID from that message (or start the run without sync: `POST /v2/acts/forlab~csv-json-schema-formatter/runs`), read its `OUTPUT` record, and fix the input — `unmapped_targets` says which fields to fix:

```json
{"status": "needs_mapping", "code": "NEEDS_MAPPING", "unmapped_targets": ["/firma", "/website"]}
```

Rows are never charged for a failed or unmapped target; only the run start is.

### Chain it after a scraper

Pass another run's dataset ID instead of pasting text (Console: the previous run's **Storage → dataset**; API: `defaultDatasetId` in the run response) and give the same **Output example** you always would. Up to 1,000 items are read as JSON records and validated like any other source:

```json
{
  "datasetId": "aBcDeFgHiJkLmNoPqRsTuV",
  "targetExample": {"title": "Example Cafe", "url": "https://example.com"}
}
```

Several runs or files? `datasetIds` / `fileUrls` merges up to 10 items into one table — see [Merge files](#merge-files).

### How it works

Leave **Output example** and **Format spec** empty and decoded rows pass straight through (a direct format conversion, e.g. XML → Excel). Give one of them and every row is shaped and validated:

1. **Name matching:** a column feeds a field when their names match, ignoring case, spaces, `_` and `-` (`Company Name` → `company_name`, `E-Mail` → `email`). Every field of the example is required, and its value sets the type: a web-address value means the field must be a URL (a missing `https://` is added), an email value a valid email.
2. **AI for the rest (optional):** a required field no column matches can be mapped by AI. The model sees only the headers and at most 5 sample rows and only says which column feeds which field; it never writes or invents values. $0.01 per run, at most once, paying users only.
3. **Validation & cleanup:** every row is validated against the target; rows that fail are reported, not returned. Any **Clean & reshape** steps (`explode`, `flatten`/`unflatten`, `filter`, `dedupeBy`, `sortBy`, `select`/`drop`, `rename`) then run in fixed order before rows are pushed or charged.

### Clean & reshape

All row operations work on both direct conversions and validated runs, in fixed order: `explode` → `flatten`/`unflatten` → `filter` → `dedupeBy` → `sortBy` → `select`/`drop` → `rename`.

```json
{
  "records": [
    {"id": 1, "meta": {"city": "Istanbul"}, "tags": ["b2b", "saas"], "score": 80},
    {"id": 2, "meta": {"city": "Ankara"}, "tags": ["b2b"], "score": 40},
    {"id": 3, "meta": {"city": "Istanbul"}, "tags": ["saas", "enterprise"], "score": 95}
  ],
  "explode": "tags",
  "flatten": true,
  "filter": [{"field": "score", "op": "gte", "value": 50}],
  "dedupeBy": ["meta.city", "tags"],
  "sortBy": ["-score"],
  "select": ["id", "meta.city", "tags", "score"],
  "rename": {"meta.city": "city"}
}
```

Output rows: `[{"id": 3, "city": "Istanbul", "tags": "enterprise", "score": 95}, {"id": 1, "city": "Istanbul", "tags": "b2b", "score": 80}, {"id": 1, "city": "Istanbul", "tags": "saas", "score": 80}]`, with `OUTPUT.removed: {"filtered": 1, "duplicates": 1}`.

### Merge files

Append several files (or datasets) into one table and drop repeated rows in one run:

```json
{
  "fileUrls": ["https://example.org/leads-istanbul.csv", "https://example.org/leads-ankara.xlsx", "https://example.org/leads-extra.json"],
  "dedupeBy": ["email"]
}
```

- Each item keeps its own format detection; rows are appended in input order (no join). Files with different columns get the union of columns, in first-seen order.
- Up to 10 items, 1,000 rows in total (`PAYLOAD_TOO_LARGE` beyond that) and 2 MiB per file. With an **Output example** or **Format spec**, the merged rows must also fit the engine's 2 MiB limit together.
- `format`, `delimiter` and `encoding` apply to every item, and an item they don't fit (for example `delimiter` on an Excel or JSON file) fails with `INVALID_REQUEST`; leave them empty to auto-detect per item.
- If an item fails, the run fails with that item's code; the log line names its position (`item`), never the URL.
- With an **Output example**, CSV/Excel items merge as one CSV (empty cells where a file lacks a column), so values are still parsed as in a single CSV. When any item is JSON, NDJSON, XML or YAML, rows merge as JSON records, and CSV/Excel cells stay text: integer and boolean target fields then reject those rows (string targets work). A **Format spec** with explicit column selectors (`col_1`) needs one source, not a merge.

### Export Markdown, HTML, SQL & JSON Schema

Request extra files through `outputFiles`: `md` (`results.md`), `html` (`results.html`), `sql` (`results.sql`, ANSI `INSERT INTO` statements with `sqlTable`, default `"data"`), and `schema` (`results.schema.json`, JSON Schema 2020-12 inferred from all output rows with merged types, `required` keys, and `email`/`uri`/`date` formats).

```json
{
  "records": [{"id": 1, "email": "ada@example.org", "note": "a | b"}],
  "outputFiles": ["md", "html", "sql", "schema"],
  "sqlTable": "users"
}
```

### HTML tables as input

Pass `"format": "html"` with pasted HTML `text` (or upload / link an `.html`/`.htm` file via `fileUrl`). The first `<table>` is extracted into tabular columns (`<th>` headers or the first row, HTML entities decoded, `colspan` ignored, scripts skipped), so it works with pass-through, `targetExample`, `formatSpec`, and tabular merge.

```json
{
  "format": "html",
  "text": "<table><thead><tr><th>Name</th><th>City</th></tr></thead><tbody><tr><td>Ada</td><td>Istanbul</td></tr></tbody></table>"
}
```

### Mapping steps (Format spec)

Use `formatSpec.mapping` for explicit field transformations, including ISO/strftime/epoch datetimes, currency strings, and Turkish-aware case conversions (`locale: "tr"`):

```json
{
  "records": [{"ts": 1763630100, "price": "₺1.234,50", "city": "İstanbul Şehir Merkezi"}],
  "formatSpec": {
    "spec_version": "1",
    "target_schema": {
      "type": "object",
      "required": ["ts", "price", "city"],
      "properties": {"ts": {"type": "string"}, "price": {"type": "number"}, "city": {"type": "string"}}
    },
    "mapping": [
      {"from": {"pointer": "/ts"}, "to": "/ts", "steps": [{"op": "parse_datetime", "epoch": "s"}]},
      {"from": {"pointer": "/price"}, "to": "/price", "steps": [{"op": "parse_currency", "locale": "tr-TR"}]},
      {"from": {"pointer": "/city"}, "to": "/city", "steps": [{"op": "snake", "locale": "tr"}]}
    ]
  }
}
```

Dataset row:

```json
{"ts": "2025-11-20T09:15:00+00:00", "price": 1234.50, "city": "istanbul_şehir_merkezi"}
```

| Operation | Parameters and semantics |
| --- | --- |
| `copy`, `trim` | Preserve JSON type, or strip surrounding Unicode whitespace from a string. |
| `lower`, `upper`, `title`, `snake`, `camel`, `kebab` | Case conversion; optional `locale` (`tr`, `tr-TR`) handles dotted/dotless `İ`/`ı`. |
| `replace_literal` | Replace every occurrence of `old` with `new`. |
| `split`, `join`, `concat` | Split a string or join a list/multiple fields with `separator`. |
| `coalesce` | Required `skip` list (`missing`, `null`, `empty`); first remaining `from_many` value wins. |
| `cast_string` | Strings pass through; other values become compact JSON text. |
| `parse_integer`, `parse_boolean` | Signed digit string, or `true`/`false` strings ignoring case. |
| `parse_decimal` | Required `locale` (`en-US`, `de-DE`, `tr-TR`); thousands grouping is checked. |
| `parse_currency` | Strips leading/trailing `₺`, `TL`, `TRY`, `$`, `USD`, `€`, `EUR`, `£`, `GBP` and parses with required `locale`. |
| `parse_date`, `format_date` | Calendar dates with `%Y`, `%m`, `%d`, `%%` (`YYYY-MM-DD`). |
| `parse_datetime` | ISO 8601 (incl. `Z`/offset), `format` (`%Y %m %d %H %M %S %b %B %%`), or `epoch` (`s` | `ms`) → ISO 8601 string. |
| `normalize_url` | Absolute HTTP(S) URL or explicit `default_scheme`; rejects userinfo. |
| `constant`, `pick_fields` | Emit a constant JSON value, or keep listed literal `fields` from an object. |

### Input

| Field | What it is |
| --- | --- |
| `text` | CSV, TSV, JSON, NDJSON/JSONL, XML, YAML, an HTML `<table>` (with `format: "html"`), or plain text (one record per line with **Source format** `text`). Use this, `records`, `fileUrl`, `fileUrls`, `datasetId`, or `datasetIds`. |
| `records` | A JSON array of objects. |
| `fileUrl` | Upload a file in Console or pass an `http(s)` URL (`.csv`, `.tsv`, `.xlsx`, `.json`, `.ndjson`, `.jsonl`, `.xml`, `.yaml`, `.yml`, `.html`, `.htm`, `.txt`). |
| `fileUrls` | Merge: up to 10 `http(s)` file URLs (mixed types allowed), appended in the order given. Use this instead of `fileUrl`. |
| `datasetId` | Read up to 1,000 items from another Apify run's dataset — chain this Actor after any scraper. |
| `datasetIds` | Merge: up to 10 datasets (pick them or paste IDs), appended in the order given. Use this instead of `datasetId`. |
| `targetExample` | One example object in the shape you want back. Leave both this and `formatSpec` empty for direct conversion without validation. |
| `useAi` | Default on. AI maps columns whose names don't match; paying users only; $0.01 per mapping. |
| `explode` | Array field to expand into one row per element (an empty list keeps the row once with `null`; missing or non-list values keep the row as is). |
| `flatten` | Flatten nested objects to `a.b` keys. |
| `unflatten` | Expand `a.b` keys back into nested objects (`INVALID_REQUEST` on key clashes). |
| `filter` | JSON array of `{field, op, value?, ignore_case?}` (`eq`, `ne`, `contains`, `not_contains`, `empty`, `not_empty`, `gt`, `gte`, `lt`, `lte`, `in`). All conditions must hold. |
| `dedupeBy` | Field names to deduplicate by, keeping the first occurrence. |
| `sortBy` | Field names to sort by (prefix `-` for descending); stable, nulls last, numbers before strings. |
| `select` | Keep only these columns, in this order. |
| `drop` | Remove these columns. |
| `rename` | JSON object mapping old column names to new names (`INVALID_REQUEST` on clashes). |
| `format` | Advanced: `csv`, `xlsx`, `json`, `ndjson`, `xml`, `yaml`, `html` or `text`. Empty auto-detects (`records` → JSON, `text` → CSV, `fileUrl`/`fileUrls` → each file's extension). One choice applies to every merged item. |
| `delimiter` | Advanced: CSV/TSV delimiter. When omitted for CSV (except `.tsv` URLs), auto-detected from `,`, `;`, `\t`, `|` over the first 20 records, falling back to `,`. |
| `encoding` | Advanced: character encoding for `fileUrl`/`fileUrls` when not UTF-8 or UTF-16 (`utf-8`, `windows-1254`, `windows-1252`, `iso-8859-9`, `iso-8859-1`). When omitted, guesses Turkish-first (`windows-1254` when Turkish bytes appear, else `windows-1252`). |
| `outputFiles` | Advanced: extra output files alongside `results.csv` and `results.xlsx` — `json` (`results.json`), `jsonl` (`results.jsonl`), `md` (`results.md`), `html` (`results.html`), `sql` (`results.sql`), and `schema` (`results.schema.json`). |
| `sqlTable` | Advanced: table name for SQL `INSERT` statements when `outputFiles` includes `sql` (1–63 characters, default `"data"`). |
| `formatSpec` | Advanced, instead of `targetExample`: a full spec with a JSON Schema target, explicit mapping rules (trim, case, split, join, number, currency, date/datetime and URL steps) and policies. |

### Format rules

- **CSV / TSV:** tries UTF-8 / UTF-8-BOM and UTF-16 with BOM, then explicit `encoding`, then a Turkish-first guess (`windows-1254` if Turkish bytes appear, else `windows-1252`). Delimiter is auto-detected from `,`, `;`, `\t`, `|` over the first 20 records unless set or `.tsv`.

- **JSON & NDJSON:** strict JSON parsing keeps decimal precision and rejects duplicate keys and `NaN`/`Infinity`. If JSON `text` or a `.json` `fileUrl` has common syntax errors (trailing commas, single quotes, unquoted keys, missing closing brackets), repair runs once before strict parsing and sets `OUTPUT.source_repaired: true`. NDJSON/JSONL reads one JSON object per non-empty line strictly and reports the line number on failure.

- **Excel (`.xlsx`):** reads the first sheet, values only; dates become ISO `YYYY-MM-DD`, whole numbers drop `.0`. Direct conversion keeps native JSON numbers, booleans, and `null` for empty cells. Duplicate headers and `.xls` files are rejected.

- **XML:** attributes and child element text become object keys (text alongside attributes uses `#text`; repeated child tags become arrays); direct children of the root element are read as records unless `record_path` is set in `formatSpec`/API source. DTDs and entities are blocked.

- **YAML:** parsed safely with anchors and aliases rejected.

- **HTML:** reads the first `<table>` using `<th>` headers or the first row, decodes HTML entities, ignores `colspan`, and skips scripts. Up to 200 columns and 1,000 rows.

### Pricing

- **$0.001 per run** (start).
- **$0.0001 per valid row** in the dataset: 1,000 valid rows cost $0.10. Rows that fail validation are free.
- **$0.01 per AI mapping**, charged at most once per run and only when the AI mapping was used and at least one valid row came out. If its proposal can't be used, the run ends `needs_mapping`, or no row passes, AI costs you nothing. It never runs on the free Apify plan, and never when your run's cost limit can't cover it plus your rows.

The run never writes more rows than your cost limit pays for; the rest are counted in `OUTPUT.charge_limit_reached_rows`.

### Limits

- Up to 1,000 rows and 2 MiB of input per run (up to 200 columns for CSV/XLSX), at most 1,000 output rows after `explode`, and an 8 MiB cap on the encoded output — pass-through runs included (`PAYLOAD_TOO_LARGE`). Merging allows up to 10 items, 2 MiB each and 1,000 rows in total.
- AI handles fields no column name matches; it only proposes plain copies and simple conversions (trim, case, text, integer, boolean).

### Status and codes

`OUTPUT.status` is `completed` (every row valid), `completed_with_errors` (some rows failed; the valid ones are in the dataset), `needs_mapping` (a required field has no column — `OUTPUT.unmapped_targets` names the fields: add a mapping in **Format spec**, rename the column, or allow AI) or `failed` with a `code`. The run fails (non-zero exit) for `needs_mapping` and `failed`.

| Code | Meaning |
| --- | --- |
| `INVALID_REQUEST` | The input is not valid: unknown field, multiple sources, more than 10 merge items, both `targetExample` and `formatSpec`, or a bad spec. |
| `INVALID_SOURCE` | The source could not be read — CSV, TSV, XLSX, JSON, NDJSON, XML, YAML, HTML or text — or it contained blocked constructs like YAML aliases or XML DTDs/entities. |
| `UNSUPPORTED_FORMAT` | Unsupported format or file extension (for example `.xls`). |
| `PAYLOAD_TOO_LARGE` | More than 1,000 rows, 2 MiB of input, or 8 MiB of output. |
| `NEEDS_MAPPING` | A required field has no column; `OUTPUT.unmapped_targets` lists the fields. |
| `INVALID_MAPPING`, `UNSUPPORTED_SCHEMA_FEATURE` | A rule or schema in **Format spec** is not supported. |
| `PLATFORM_ERROR`, `INTERNAL_ERROR` | An Apify call or the run itself failed; try again. |

`ai_off_reason`: `AI_OFF_BY_INPUT`, `AI_FREE_PLAN`, `AI_NO_KEY` or `AI_NOT_PRICED` (AI is not available right now), `AI_BUDGET_TOO_LOW` (your cost limit can't cover it), or an AI failure code (`AI_LIMIT_REACHED`, `AI_UNAVAILABLE`, …), after which the run continued with name matching only.

# Actor input Schema

## `text` (type: `string`):

Paste CSV (or TSV), JSON (common syntax errors repaired automatically), NDJSON/JSONL, XML, YAML, an HTML <table> (with format html), or plain text (one record per line, with format text). Use this OR records, fileUrl, fileUrls, datasetId, datasetIds. Up to 1,000 rows and 2 MiB per run.

## `records` (type: `array`):

An array of JSON objects. Use this OR text, fileUrl, fileUrls, datasetId, datasetIds. Up to 1,000 records and 2 MiB per run.

## `fileUrl` (type: `string`):

Upload a CSV, TSV, Excel (.xlsx), JSON, NDJSON/JSONL (.ndjson, .jsonl), XML, YAML, or HTML (.html, .htm) file, or paste its http(s) URL. Use this OR text, records, fileUrls, datasetId, datasetIds. Up to 1,000 rows and 2 MiB.

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

Up to 10 http(s) URLs of CSV, TSV, Excel (.xlsx), JSON, NDJSON/JSONL, XML, YAML, or HTML files (mixed types allowed) to append into one table, in the order given. Each file is read on its own (own delimiter and encoding detection) and must be 2 MiB or less; the merged result is capped at 1,000 rows. Rows with different columns get the union of columns. Combine with Deduplicate by fields to merge and dedupe. Use this OR text, records, fileUrl, datasetId, datasetIds.

## `targetExample` (type: `object`):

One example object in the shape you want back. Every key becomes a required output field; the value's type sets the field type (a URL value means a web address, an email value an email). Leave both this and Format spec empty to convert the input directly without schema checks. Use this OR the advanced format spec.

## `useAi` (type: `boolean`):

AI maps columns whose names don't match; paying users only; $0.01 per mapping. It runs only when name matching leaves a field unmapped, sees the headers and at most 5 sample rows, and only proposes which column feeds which field: it never writes values. Charged once per run, only when its mapping was used and at least one valid row came out.

## `explode` (type: `string`):

Top-level array field to expand into one row per element (for example "items"). An empty list keeps the row once with null; rows where the field is missing or not an array stay as is. Output is still capped at 1,000 rows.

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

Turn nested objects into top-level keys joined by dots (for example address.city).

## `unflatten` (type: `boolean`):

Turn dotted top-level keys (such as address.city) back into nested objects. Fails with INVALID_REQUEST on key clashes (for example a and a.b).

## `filter` (type: `array`):

Conditions that every kept row must satisfy (JSON array of {field, op, value?, ignore_case?}). Supported ops: eq, ne, contains, not_contains, empty, not_empty, gt, gte, lt, lte, in. Example: \[{"field": "country", "op": "eq", "value": "TR", "ignore_case": true}, {"field": "score", "op": "gte", "value": 50}]. Removed rows are never pushed or charged.

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

Field names used to detect duplicates; keeps the first matching row. Removed duplicates are never pushed or charged. (When Flatten is enabled, use dotted keys such as address.city.)

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

Field names to sort by in priority order. Prefix a field name with - for descending order (for example -score). Nulls and missing values sort last; numbers sort before strings.

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

Keep only these fields in the given order. Missing fields on a row are omitted.

## `drop` (type: `array`):

Field names to remove from every row.

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

JSON map of old column names to new names, for example {"old_name": "new_name"}. Renaming onto an existing column fails with INVALID_REQUEST.

## `format` (type: `string`):

Leave empty to auto-detect: records means JSON, text means CSV, fileUrl and fileUrls use each file's extension (.csv, .tsv, .xlsx, .json, .ndjson, .jsonl, .xml, .yaml, .html, .htm, .txt). Choose explicitly for json, ndjson, yaml, xml, html, text, or extensionless URLs. With several files, one choice applies to all of them.

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

Select a dataset or paste its ID from another Apify run (up to 1,000 items). Use this OR text, records, fileUrl, fileUrls, datasetIds.

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

Select up to 10 datasets (or paste their IDs) from other Apify runs to append into one table, in the order given. The merged result is capped at 1,000 rows. Rows with different fields get the union of fields. Combine with Deduplicate by fields to merge and dedupe. Use this OR text, records, fileUrl, fileUrls, datasetId.

## `delimiter` (type: `string`):

One character. When omitted for CSV (except .tsv URLs), auto-detected from , ; \t | over the first 20 records, falling back to comma.

## `encoding` (type: `string`):

Character encoding for fileUrl and fileUrls when it is not UTF-8 or UTF-16. Leave empty to guess Turkish Windows-1254 first, then Windows-1252.

## `outputFiles` (type: `array`):

Additional files to write alongside results.csv and results.xlsx: json (pretty-printed JSON array), jsonl (one JSON object per line), md (Markdown table), html (HTML table), sql (ANSI INSERT statements), and schema (inferred JSON Schema 2020-12).

## `sqlTable` (type: `string`):

Table name for SQL INSERT statements when outputFiles includes sql (1–63 characters, no NUL, default "data").

## `formatSpec` (type: `object`):

The full format_spec of the Formatter API: a JSON Schema target (target_schema) or target_example, explicit mapping rules with transform steps (including parse_datetime, parse_currency, title/snake/camel/kebab), and policies (row_error collect or fail). OUTPUT's added_mapping can be saved here to pin the mapping for later files.

## Actor input object example

```json
{
  "text": "Company Name,Web Site,E-Mail\nOrnek Ltd,ornek.example,bilgi@ornek.example\nAcme Inc,https://acme.example,sales@acme.example\n",
  "targetExample": {
    "company_name": "Ornek Ltd",
    "website": "https://ornek.example",
    "email": "bilgi@ornek.example"
  },
  "useAi": true,
  "flatten": false,
  "unflatten": false,
  "sqlTable": "data"
}
```

# Actor output Schema

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

One item per valid input row in input order. Invalid rows are not here; OUTPUT says why each failed.

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

Formatted rows as a UTF-8 CSV file in target column order.

## `xlsx` (type: `string`):

Formatted rows as an Excel (.xlsx) workbook in target column order.

## `json` (type: `string`):

Pretty-printed UTF-8 JSON array, written when outputFiles includes json.

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

One JSON object per line, written when outputFiles includes jsonl.

## `md` (type: `string`):

GitHub-flavored Markdown table in target column order, written when outputFiles includes md.

## `html` (type: `string`):

Minimal HTML document with one <table> in target column order, written when outputFiles includes html.

## `sql` (type: `string`):

ANSI SQL INSERT statements in target column order, written when outputFiles includes sql.

## `schema` (type: `string`):

JSON Schema 2020-12 inferred from all output rows, written when outputFiles includes schema.

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

Status and code, row counts, the per-row report with issues, the mapping the run added, and whether AI ran or why not.

# 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 = {
    "text": `Company Name,Web Site,E-Mail
Ornek Ltd,ornek.example,bilgi@ornek.example
Acme Inc,https://acme.example,sales@acme.example`,
    "targetExample": {
        "company_name": "Ornek Ltd",
        "website": "https://ornek.example",
        "email": "bilgi@ornek.example"
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("forlab/csv-json-schema-formatter").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 = {
    "text": """Company Name,Web Site,E-Mail
Ornek Ltd,ornek.example,bilgi@ornek.example
Acme Inc,https://acme.example,sales@acme.example
""",
    "targetExample": {
        "company_name": "Ornek Ltd",
        "website": "https://ornek.example",
        "email": "bilgi@ornek.example",
    },
}

# Run the Actor and wait for it to finish
run = client.actor("forlab/csv-json-schema-formatter").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 '{
  "text": "Company Name,Web Site,E-Mail\\nOrnek Ltd,ornek.example,bilgi@ornek.example\\nAcme Inc,https://acme.example,sales@acme.example\\n",
  "targetExample": {
    "company_name": "Ornek Ltd",
    "website": "https://ornek.example",
    "email": "bilgi@ornek.example"
  }
}' |
apify call forlab/csv-json-schema-formatter --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,forlab/csv-json-schema-formatter"
        }
    }
}
```

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/Ndanosg65CmrDFsmL/builds/xCqvgL5k77vysc62h/openapi.json
