# Dataset Type Caster: fix CSV & JSON column types (`ucchiii/dataset-type-caster`) Actor

Turns text columns of a CSV / JSON file or Apify dataset into integers, numbers, booleans, ISO dates, trimmed text or null. Reads 1,200 / 1.234,50 / ¥ / full-width digits and Japanese era dates (R5.4.1). Bad cells are listed per row. Empty input = free demo.

- **URL**: https://apify.com/ucchiii/dataset-type-caster.md
- **Developed by:** [Actor Factory](https://apify.com/ucchiii) (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.14 / 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

**Convert the column types of a CSV, JSON file or Apify dataset**

**Turns text into real numbers, booleans and dates, and tells you exactly which cells it could not read.** For anyone whose data arrives as text: a scraper dataset where every price is `"¥1,200"` or `"1.234,50"`, a CSV export with `yes`/`no` and `はい`/`いいえ`, order dates written `R5.4.1`, `2024年4月1日` or `13/04/2024`, `N/A` and `-` where a value is missing. Name the columns and their types, press Start, and download the converted rows as CSV, JSON or Excel from the dataset (or as one CSV file). It works from the Console form: no code, no spreadsheet formulas.

**Try it free: leave all inputs empty and press Start** (the demo is not charged and its rows carry `_demo: true`).
**$0.20 per 1,000 output rows**, charged per row ($0.0002 a row). Converting 5,000 rows costs $1.00. The $5 monthly free credit covers about 25,000 output rows. Reading rows is free. Rows left out because of a bad cell (when you choose that) are not charged. Failed runs and the demo are free. No scraping, no API keys.

### Sample

Input rows (a dataset or a CSV file), **Casts**:
`[{"column": "price", "type": "number"}, {"column": "qty", "type": "integer"}, {"column": "paid", "type": "boolean"}, {"column": "ordered", "type": "date"}]`

| price | qty | paid | ordered |
|---|---|---|---|
| ¥1,200 | 3 | はい | R5.4.1 |
| 1.234,50 | １２ | no | 2024年4月2日 |
| (45.00) | 2 pcs | maybe | 03/04/2024 |

Output (with the default **Keep the original value** for unreadable cells):

| price | qty | paid | ordered | \_castErrors |
|---|---|---|---|---|
| 1200 | 3 | true | 2023-04-01 | |
| 1234.5 | 12 | false | 2024-04-02 | |
| -45 | 2 pcs | maybe | 03/04/2024 | `["qty", "paid", "ordered"]` |

`2 pcs` is not a whole number, `maybe` is not a yes/no word, and `03/04/2024` could be 3 April or 4 March, so those three cells stay as they were and their column names are listed in `_castErrors`. Rows without a problem have no `_castErrors`.

### What it does

- **integer**: whole numbers. Understands `1,200`, `1.234.567`, `1 200`, `¥1,200`, `$5`, `5円`, `USD 5`, `(45)` and `▲45` (negative), `45-`, and full-width digits such as `１２３`. A value with decimals (`12.5`) is an error unless you set the option **fraction** to `round`, `floor`, `ceil` or `trunc`.
- **number**: the same, with decimals. The decimal separator is read as `.` or `,` automatically (`1,234.50`, `1.234,50` and `12,5` all work); set the option **decimal** to `.` or `,` when you know it. `1,200` is read as 1200 and `1.200` as 1.2 unless you set **decimal**. Percent values (`12%`) are an error unless the option **percent** is `divide` (0.12) or `strip` (12).
- **boolean**: `true/false`, `yes/no`, `y/n`, `t/f`, `on/off`, `1/0`, `はい/いいえ`, `真/偽`, `○/×`, any case. Give your own words with the options **trueValues** and **falseValues** (they replace the defaults).
- **date**: written out as ISO 8601. Reads `2024-04-01`, `2024/4/1`, `2024.04.01`, `20240401`, `4 Mar 2026`, `March 4, 2026`, `2024-04-01T10:00:00Z`, Japanese dates such as `2024年4月1日`, and **Japanese era dates** such as `R5.4.1`, `令和5年4月1日`, `H31.4.30`, `令和元年5月1日` (Meiji, Taisho, Showa, Heisei and Reiwa; a date outside its era, such as `H31.5.1`, is an error). Dates like `03/04/2024` are read only when it is clear which part is the day (`13/04/2024`) or when you set **dateOrder** to `dmy` or `mdy`; otherwise they are an error rather than a guess. Dates with dots (`04.03.2026`) are day first. Two-digit years: 00-69 mean 2000-2069, 70-99 mean 1970-1999. Set **inputFormats** to your own strptime patterns (for example `["%d/%m/%Y", "auto"]`), and **outputFormat** to `iso` (the default, `2024-04-01`), `iso-datetime` or any strftime pattern such as `%d/%m/%Y`. A time of day in the input is dropped unless the output format keeps it.
- **string**: trim (on by default), `upper`/`lower` case, collapse repeated spaces, normalise full-width characters to half-width. Numbers become text (`5` becomes `"5"`).
- **null**: the strings you list become real `null` (default list: empty, `N/A`, `NA`, `null`, `none`, `nan`, `-`, `--`, `—`; any case). Other values stay as they are.
- **Empty cells** (empty text, only spaces, or already null) become `null` for integer, number, boolean and date, and are not counted as errors.
- **Several casts for one column** apply in the order given: first make `N/A` null, then cast the column to number.
- **Two kinds of input**: Apify datasets (resource picker, read permission only) and public CSV / TSV / JSON / NDJSON file URLs, mixed freely. Encoding (UTF-8, Shift JIS, Windows-1252) and delimiter (comma, semicolon, tab, pipe) are detected. Columns you do not list come out unchanged.

### Input example

```json
{
  "fileUrls": ["https://raw.githubusercontent.com/mwaskom/seaborn-data/master/titanic.csv"],
  "casts": [
    {"column": "survived", "type": "boolean"},
    {"column": "age", "type": "integer", "options": {"fraction": "round"}},
    {"column": "fare", "type": "number"}
  ],
  "onError": "keep"
}
```

Short form: `"casts": ["price:number", "paid:boolean", "ordered:date"]`.

### Output

- **Dataset**: one row per input row, in the input order, with the cast columns. Download as CSV, JSON, Excel and more from the Console.
- **`_castErrors`**: on every row that had an unreadable cell, the list of the column names that failed.
- **`cast.csv`** (key-value store, only with **Also save a CSV file**).
- **`FAILED_ROWS`** (key-value store, only with **Leave the whole row out** when a row failed): the first 1,000 left-out rows with the reason per cell.
- **STATS** record (key-value store): `inputRows`, `outputRows`, `chargedRows`, `rowsWithErrors`, `cellErrors`, rows read per source, per column how many cells were cast, emptied and failed, and up to 20 examples of unreadable values with the row number and the reason.

### If a cell cannot be read

Choose **If a cell cannot be read**:

- **Keep the original value** (default): the cell stays as it was, the column name goes into `_castErrors`.
- **Set the cell to null**: the cell becomes `null`, the column name goes into `_castErrors`.
- **Leave the whole row out**: the row is not written and not charged. The first 1,000 such rows are saved in `FAILED_ROWS` with the reason.

### Limits (cannot be raised by input)

- **Up to 200,000 input rows per run.** If there are more rows than **Max input rows**, the run stops without converting or charging rather than giving you a half-converted table. Split the data first.
- 20 datasets and files per run; 100 MB per file (a JSON array: 50 MB, because it has to be read whole; use NDJSON, one object per line, for bigger files); 50 casts.
- Columns are top-level names (case-sensitive). Nested values cannot be cast, except to text as JSON for a CSV copy.
- Whole numbers and numbers up to 9,007,199,254,740,991 (larger values are an error, because they would lose digits in JSON).
- Source URLs must be public `http` or `https` links. Addresses on internal networks (localhost, private ranges, cloud metadata) are blocked, also after redirects. Excel files are not read (save them as CSV first).

### Pricing

Pay per event: **$0.20 per 1,000 output rows** (event `row`, $0.0002 per output row). Reading input rows is free. Nothing is charged when the run fails, for the demo, or for rows left out. Set a maximum charge per run: the Actor then writes only the first rows that fit the budget (never past it) and says so in the run summary. If the budget is lower than the price of one row, the run stops at once without charging.
On the Apify Free plan, the $5 of monthly platform credit covers about **25,000 rows** a month.

### Use cases

- Make scraped prices, ratings and counts into numbers before sorting, filtering or charting them
- Clean a CSV export before an import: `yes`/`no` to true/false, `N/A` to empty, dates to ISO 8601
- Read Japanese business files: era dates, full-width digits, `円`, `▲` negatives
- Find the bad cells: with the default setting, filter on `_castErrors` to see what needs a human
- Prepare typed, consistent columns for the next Actor in a workflow

### FAQ

**Does it change my source dataset?** No. It only reads it and writes a new dataset.
**Why is a cell unchanged?** It could not be read as the chosen type. Look for `_castErrors` on the row, and the examples in the run summary.
**Why did `1.200` become 1.2?** A single dot is read as a decimal point. Set the option **decimal** to `,` if your numbers use dots for thousands.
**Why is `03/04/2024` an error?** It could be 3 April or 4 March. Set **dateOrder** to `dmy` or `mdy` and it is read.
**Do I get 1200 or 1200.0?** Whole values come out as whole numbers (`1200`), others with decimals (`1234.5`).
**Can I rename a column or change a column and keep the old one?** No. The cast replaces the value in the same column.

If this Actor saved you time, a rating on the Store helps others find it.

### More tools from the same developer

- [Filter CSV, JSON or Dataset Rows by Condition](https://apify.com/ucchiii/filter-rows) — keep only the rows of a CSV, JSON file or dataset that match simple conditions like country = US or price > 100
- [Dataset Sort](https://apify.com/ucchiii/dataset-sort) — sort a CSV, JSON file or dataset by one or more columns: numbers, text or dates, natural order, top-N and dedupe
- [CSV to JSON Converter](https://apify.com/ucchiii/csv-to-json) — turn CSV files into typed JSON: encoding and delimiter detected, numbers and booleans typed, dotted headers nested, array, NDJSON or keyed output
- [Merge Datasets](https://apify.com/ucchiii/merge-datasets) — combine several datasets or CSV/JSON files into one, with columns aligned
- [CSV Encoding Converter](https://apify.com/ucchiii/csv-encoding-converter) — detect the encoding of CSV and text files and convert them to UTF-8 (or another encoding)

# Actor input Schema

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

Datasets to convert (the 'defaultDatasetId' of a finished run). You can paste a dataset URL from Apify Console too. Several datasets and files are read in the order given and come out as one table. Up to 20 in total. Leave this and 'File URLs' empty to run a free demo on a built-in sample (not charged).

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

Public http(s) links to CSV, TSV, JSON or NDJSON files (up to 100 MB each; a JSON array up to 50 MB, use NDJSON for bigger files). The encoding (UTF-8, Shift JIS, Windows-1252) and the delimiter are detected. Links to internal networks are blocked.

## `casts` (type: `array`):

The columns to convert. Each entry is "column:type", or an object {"column": ..., "type": ..., "options": {...}}. Types: integer, number, boolean, date, string, null. Options per type: integer/number {decimal: auto|.|, , percent: error|strip|divide} and integer {fraction: error|round|floor|ceil|trunc}; boolean {trueValues, falseValues}; date {inputFormats (strptime codes or "auto"), dateOrder: auto|dmy|mdy, outputFormat: iso|iso-datetime|a strftime pattern}; string {trim, case: none|upper|lower, collapseSpaces, normalize}; null {values: \["N/A", "-"], ignoreCase}. Empty cells become null for integer, number, boolean and date. Several entries for one column apply in the order given (first make "N/A" null, then cast to number). Required unless you run the demo.

## `onError` (type: `string`):

What happens to a value that cannot be read as the chosen type (for example 'abc' in a number column). Every row that had such a cell carries '\_castErrors', a list of the column names that failed (not with 'Leave the row out': those rows are not written and not charged; the first 1,000 are saved in the record FAILED_ROWS with the reason). The run summary lists examples. Default: keep.

## `outputCsv` (type: `boolean`):

Besides the dataset, save the cast rows as one CSV file in the key-value store (record 'cast.csv', UTF-8 with BOM so Excel opens it correctly). The file is built in memory. Nested values are written as JSON text. Default: off.

## `maxInputRows` (type: `integer`):

Safety limit on the rows read across all sources. If there are more rows than this the run stops without converting or charging (it never gives you a half-converted table). Maximum and default: 200,000.

## Actor input object example

```json
{
  "fileUrls": [
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/titanic.csv"
  ],
  "casts": [
    {
      "column": "survived",
      "type": "boolean"
    },
    {
      "column": "age",
      "type": "integer",
      "options": {
        "fraction": "round"
      }
    },
    {
      "column": "alive",
      "type": "boolean"
    },
    {
      "column": "fare",
      "type": "number"
    }
  ],
  "onError": "keep",
  "outputCsv": false,
  "maxInputRows": 200000
}
```

# Actor output Schema

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

The rows with the cast columns, in the input order. Rows with unreadable cells carry \_castErrors. Download as CSV, JSON, Excel and more.

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

The cast rows as one CSV file (UTF-8 with BOM, opens correctly in Excel). Only exists when 'Also save a CSV file' is on.

## `failedRows` (type: `string`):

Record FAILED_ROWS: the input rows that were left out because a cell could not be read, with the reason per cell. Only exists when 'If a cell cannot be read' is 'Leave the row out' and a row failed.

## `stats` (type: `string`):

Record STATS: rows read per source, rows written and charged, per column how many cells were cast, emptied or failed, and examples of unreadable values.

# 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/mwaskom/seaborn-data/master/titanic.csv"
    ],
    "casts": [
        {
            "column": "survived",
            "type": "boolean"
        },
        {
            "column": "age",
            "type": "integer",
            "options": {
                "fraction": "round"
            }
        },
        {
            "column": "alive",
            "type": "boolean"
        },
        {
            "column": "fare",
            "type": "number"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("ucchiii/dataset-type-caster").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/mwaskom/seaborn-data/master/titanic.csv"],
    "casts": [
        {
            "column": "survived",
            "type": "boolean",
        },
        {
            "column": "age",
            "type": "integer",
            "options": { "fraction": "round" },
        },
        {
            "column": "alive",
            "type": "boolean",
        },
        {
            "column": "fare",
            "type": "number",
        },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("ucchiii/dataset-type-caster").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/mwaskom/seaborn-data/master/titanic.csv"
  ],
  "casts": [
    {
      "column": "survived",
      "type": "boolean"
    },
    {
      "column": "age",
      "type": "integer",
      "options": {
        "fraction": "round"
      }
    },
    {
      "column": "alive",
      "type": "boolean"
    },
    {
      "column": "fare",
      "type": "number"
    }
  ]
}' |
apify call ucchiii/dataset-type-caster --silent --output-dataset

```

## MCP server setup

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

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/eKnPGyw2DVN2mstsZ/builds/rFGTFCl6bEQp29PWE/openapi.json
