# CSV to JSON Converter with Schema Inference & Validation (`nibble/csv-json-schema-converter`) Actor

Convert CSV files to clean, typed JSON. Auto-detects delimiter, infers a JSON Schema, and validates rows against your own schema. Ideal for APIs, data pipelines and AI agents.

- **URL**: https://apify.com/nibble/csv-json-schema-converter.md
- **Developed by:** [Simon Fletcher](https://apify.com/nibble) (community)
- **Categories:** Developer tools
- **Features:** Limited permissions
- **Stats:** 8 total users, 0 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 converted files

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

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

### What does the CSV to JSON Converter do?

**CSV to JSON Converter** turns messy CSV files into **clean, typed JSON** you can drop straight into an API, a database, or an AI agent. It **auto-detects the delimiter** (comma, semicolon, tab or pipe), **infers value types** (integer, number, boolean, null), builds a **JSON Schema** describing your data, and can **validate every row against a schema you provide**. Give it a URL, an uploaded file, or raw CSV text — it gives back structured records, not a wall of strings.

Running on Apify means you get an HTTP API, scheduling, [integrations](https://apify.com/integrations) (Make, Zapier, n8n, Google Drive), run history, and access from the [Apify MCP server](https://mcp.apify.com/) so AI agents can call it directly.

### Why use the CSV to JSON Converter?

- **Feed APIs and pipelines** — convert exports from spreadsheets, banks, CRMs and analytics tools into JSON your code can consume.
- **Give AI agents clean data** — the output is compact structured JSON (no HTML, no nested junk), ideal for LLM tool use over the Apify MCP.
- **Catch bad data early** — supply a target JSON Schema and get a per-row validation report instead of silent corruption.
- **Stop hand-writing parsers** — delimiter sniffing, quoted fields, embedded newlines, ragged rows and encodings are handled for you.

### How to use the CSV to JSON Converter

1. Open the **Input** tab.
2. Provide your CSV one of three ways: paste **inline CSV text**, add **file URLs**, or **upload files** (delivered via key-value-store keys).
3. (Optional) Set a delimiter, toggle header/type inference, or paste a **target JSON Schema** to validate against.
4. Click **Start**. Each input file becomes one dataset item you can download as JSON, CSV, Excel or HTML.

### Input

| Field | Type | Description |
|-------|------|-------------|
| `csvUrls` | array | Public URLs of CSV files to download and convert. |
| `keyValueStoreKeys` | array | Keys of uploaded files in the run's key-value store. |
| `csvText` | array | Raw CSV strings passed inline (great for API / agent callers). |
| `delimiter` | string | Force a delimiter. Blank = auto-detect `, ; \t \|`. |
| `hasHeader` | boolean | Treat the first row as column names (default true). |
| `inferTypes` | boolean | Coerce to integer/number/boolean/null (default true). |
| `trimWhitespace` | boolean | Strip whitespace from every cell (default true). |
| `nullValues` | array | Values to treat as null (**replaces** the default set: empty, NA, N/A, null, nan, none). |
| `maxRows` | integer | Cap data rows per file (0/blank = no cap). |
| `targetSchema` | object | JSON Schema (Draft 2020-12) for a single row; enables per-row validation. |

#### Example input

```json
{
  "csvText": ["id,name,active,score\n1,Ada,true,9.5\n2,Grace,false,8.0"],
  "inferTypes": true
}
```

### Output

Each input file produces **one dataset item**. You can download the dataset as JSON, CSV, Excel or HTML.

```json
{
  "source": "csvText[0]",
  "status": "ok",
  "error": null,
  "rowCount": 2,
  "columnCount": 4,
  "columns": ["id", "name", "active", "score"],
  "records": [
    { "id": 1, "name": "Ada",   "active": true,  "score": 9.5 },
    { "id": 2, "name": "Grace", "active": false, "score": 8.0 }
  ],
  "inferredSchema": {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "array",
    "items": {
      "type": "object",
      "properties": {
        "id":     { "type": "integer" },
        "name":   { "type": "string" },
        "active": { "type": "boolean" },
        "score":  { "type": "number" }
      }
    }
  },
  "validation": { "checked": false, "valid": true, "validRows": 2, "invalidRows": 0, "errors": [] },
  "meta": { "delimiter": ",", "hasHeader": true, "typesInferred": true, "encoding": "utf-8", "emptyRowsSkipped": 0, "raggedRows": 0 }
}
```

#### Output fields

| Field | Description |
|-------|-------------|
| `source` | Where the file came from (URL, KVS key, or `csvText[i]`). |
| `status` | `ok` when converted, `error` when unreadable/empty. |
| `rowCount` / `columnCount` | Converted data-row and column counts. |
| `columns` | Ordered column names (header names or `field_N`). |
| `records` | The converted rows as typed JSON objects. |
| `inferredSchema` | JSON Schema describing the records. |
| `validation` | Per-row report vs your `targetSchema` (`checked=false` when none). |
| `meta` | Delimiter, encoding, header flag, blank/ragged row counts. |

### Pricing / How much does it cost?

This Actor is billed **pay-per-result**: one charge per file that converts into non-empty data. A file that is empty, unreadable, or has no data rows is returned with `status: "error"` and is **never charged**. See the Pricing tab for the current per-result rate. Converting a handful of files costs a fraction of a cent of platform compute; the value is in never writing another CSV parser.

### Tips & advanced options

- **Leading zeros are preserved.** Values like `01234` or `00080` stay strings so zip codes, phone numbers and IDs are never corrupted into integers. Type inference is **per cell**, so a column with mixed values (e.g. `01234` and `90210`) can contain both strings and integers — set `inferTypes: false` to keep every value a string.
- **Ragged rows are lossless.** Rows with more cells than the header get extra columns named `field_N` rather than dropping data.
- **Validation.** Paste a `targetSchema` to get a `validation` block flagging exactly which rows and fields don't match — without failing the whole run.
- **Big files.** Each file is returned as one dataset item, and Apify caps a single item at ~9 MB. A file whose converted JSON would exceed that is returned as a clear (unbilled) size-cap error — use `maxRows` to convert it in smaller batches, or sample the top of a large file cheaply.

### FAQ & support

- **What formats can I export?** JSON, CSV, Excel and HTML, from the dataset.
- **Does it store my data?** Only in your run's own dataset/key-value store, under your account.
- **Known limitation:** type inference is per-cell (see Tips). Column-level type unification is a planned option.
- Found a bug or want a feature? Use the **Issues** tab.

# Actor input Schema

## `csvUrls` (type: `array`):

Public URLs of CSV files to convert. Each is downloaded (with retries) and converted to structured JSON. Example: https://people.sc.fsu.edu/~jburkardt/data/csv/hw_200.csv

## `keyValueStoreKeys` (type: `array`):

Keys in this run's default key-value store that hold CSV bytes. This is how files uploaded via the Console form are passed to the Actor.

## `csvText` (type: `array`):

Raw CSV strings passed inline — convenient for API or AI-agent callers that send the data directly instead of by URL.

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

Column delimiter. Leave blank to auto-detect comma, semicolon, tab or pipe.

## `hasHeader` (type: `boolean`):

Treat the first row as column names. If off, columns are named field_1, field_2, …

## `inferTypes` (type: `boolean`):

Coerce cells to integer / number / boolean / null. Leading-zero values (e.g. 007, 01234) are kept as strings to protect IDs and zip codes. Turn off to keep every value a string.

## `trimWhitespace` (type: `boolean`):

Strip leading/trailing whitespace from every cell before conversion.

## `nullValues` (type: `array`):

Cell values (case-insensitive) to treat as null. Defaults to empty, NA, N/A, null, nan, none.

## `maxRows` (type: `integer`):

Cap the number of data rows converted per file (0 or blank = no cap).

## `targetSchema` (type: `object`):

Optional JSON Schema (Draft 2020-12) for a single row/object. When set, every converted row is validated against it and a per-row validation report is returned.

## Actor input object example

```json
{
  "csvText": [
    "id,name,active,score\n1,Ada,true,9.5\n2,Grace,false,8.0"
  ],
  "hasHeader": true,
  "inferTypes": true,
  "trimWhitespace": true
}
```

# 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 = {
    "csvText": [
        "id,name,active,score\n1,Ada,true,9.5\n2,Grace,false,8.0"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("nibble/csv-json-schema-converter").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 = { "csvText": ["""id,name,active,score
1,Ada,true,9.5
2,Grace,false,8.0"""] }

# Run the Actor and wait for it to finish
run = client.actor("nibble/csv-json-schema-converter").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 '{
  "csvText": [
    "id,name,active,score\\n1,Ada,true,9.5\\n2,Grace,false,8.0"
  ]
}' |
apify call nibble/csv-json-schema-converter --silent --output-dataset

```

## MCP server setup

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

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/h81ZaRolvH1o9w8uw/builds/nk2ffYRu5hZ2ge6gm/openapi.json
