# Flatten JSON to CSV: Nested to Flat Rows, Any Separator (`ucchiii/flatten-json`) Actor

Returns one flat row per nested JSON item (names like seller.location.city) from Apify datasets, a JSON or NDJSON URL, or pasted JSON, ready to download as CSV or Excel. Pick the key separator (. \_ \_\_ /), how arrays are written and how deep to flatten. Empty input = free demo.

- **URL**: https://apify.com/ucchiii/flatten-json.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.11 / 1,000 flattened 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

**Flatten JSON: returns one flat row per nested JSON item, with one column per field (`seller.location.city`), ready for CSV, Excel or a database.**

- **Cost:** $0.15 per 1,000 rows, no start fee. **The $5 monthly free credit covers about 33,000 rows.**
- **Output example:** see *What you get* below — one input item, one flat row.

Scrapers and APIs return nested data like `{"seller": {"location": {"city": "Seattle"}}}`. Spreadsheets and SQL tables want flat columns like `seller.location.city`. Point this Actor at one or more **Apify datasets**, a **JSON / NDJSON URL** or **paste JSON**, and every item comes back as one flat row in your dataset — then download it as CSV, Excel, JSON or XML from the run page, or pass it to the next Actor. You choose the key separator, how arrays are written and how deep to flatten. You pay per flattened row only, with no start fee.

**Try it free:** leave the input empty and press **Start** — 3 built-in nested product records are flattened (not charged; rows carry `_demo: true`).

### What you get

Input item:

```json
{"id": 101, "price": {"amount": 49.9, "currency": "USD"},
 "seller": {"name": "Northwind Traders", "location": {"country": "US", "city": "Seattle"}},
 "categories": ["electronics", "accessories"], "variants": [{"color": "black", "stock": 12}]}
```

Flat row (default separator `.`, arrays as JSON text):

| id | price.amount | price.currency | seller.name | seller.location.country | seller.location.city | categories | variants |
|---|---|---|---|---|---|---|---|
| 101 | 49.9 | USD | Northwind Traders | US | Seattle | \["electronics", "accessories"] | \[{"color": "black", "stock": 12}] |

With **Key separator** `_` and **Arrays** `join`: `seller_location_city` = `Seattle`, `categories` = `electronics; accessories`.

### How to use

1. **One kind of source**: **Datasets to flatten** (one or more IDs or URLs, for example scrapers' results — with several datasets each row gets `_source` with its dataset ID), **or** a **JSON / NDJSON URL** (a JSON array, an object holding one array like `{"data": [...]}`, or one object per line), **or** **paste JSON** (up to 10,000 items).
2. **Key separator** — `.` (default), `_`, `__`, `/` or any 1–5 characters.
3. **Arrays** — `json` keeps a list as JSON text in one column; `join` writes plain values as `a; b` (set your own **Join separator**). Lists of objects stay JSON text either way, so no data is lost.
4. Optional: **Maximum depth** (deeper parts stay JSON text in one column) and **Stop after this many rows** (to try settings on a big dataset).

```json
{
  "datasetIds": ["https://console.apify.com/storage/datasets/AbCdEf123"],
  "separator": "_",
  "arrays": "join",
  "joinSeparator": ", "
}
```

### Output

- **Dataset**: one flat item per input item, in the original order. Numbers, `true`/`false` and `null` keep their type; empty objects and empty lists become `null`. Items that are not objects (a bare string or number) become `{"value": ...}`.
- **STATS** record: source, separator, rows written and charged, every column name seen, whether the run stopped early, and notes (for example when two keys flatten to the same name — the first value is kept and the clash is counted).

### Limits (cannot be raised by input)

- **1,000,000 rows** per run; JSON / NDJSON files up to **500 MB**; a file that is one object wrapping the rows up to **20 MB**; pasted JSON up to 10,000 items; 2,000 fields per row.
- Public files only, no login. Links to internal network addresses are blocked. Files must be UTF-8.
- Set a maximum cost per run to cap spend: the Actor stops cleanly when it is reached (status Succeeded), keeps the rows written so far and says so in the status message and STATS (`stoppedEarly: "max_charge"`).
- If a file has broken JSON in the middle, the rows before the break are kept (and charged); the rest is skipped and the run says where it stopped.

### Pricing

Pay per event: **$0.00015 per flattened row** ($0.15 per 1,000 rows), with no start fee. Flattening a 10,000-item dataset costs $1.50. Items that cannot be read, failed runs and the demo are free.
Store discounts apply automatically: BRONZE −10%, SILVER −20%, GOLD −30%.
On the Apify Free plan, the $5 of monthly platform credit covers about 33,000 rows a month.

### FAQ

**Can I get one CSV file with a link instead of dataset rows?** Use the JSON to CSV Actor from the same developer — it writes a single CSV file with a download link and lets you choose the column order.

**Does it split arrays into several rows?** No. This Actor only flattens: one input item gives exactly one output row, so row counts always match your source.

**Why `seller.location.city` and not `seller/location/city`?** That is the default. Set **Key separator** to `/` (or `_` for SQL-friendly names).

**Is my data changed?** Only the shape. Values are copied as they are; nothing is rounded, translated or filtered out.

### More tools from the same developer

- [JSON to CSV Converter](https://apify.com/ucchiii/json-to-csv) — turn nested JSON files or datasets into one flat CSV file
- [Dataset Explode & Unpivot](https://apify.com/ucchiii/dataset-explode-unpivot) — explode array fields into rows, unpivot wide columns into name/value rows, or pivot back
- [Dataset Transform](https://apify.com/ucchiii/dataset-transform) — flatten, filter, rename and convert any Apify dataset, export CSV / JSON / JSONL with a link
- [CSV to Excel Converter](https://apify.com/ucchiii/csv-xlsx-converter) — convert CSV, TSV, Excel XLSX, JSON and NDJSON files or Apify datasets into each other

# Actor input Schema

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

Apify datasets with nested items, for example the results of scraper runs (up to 100). You can paste dataset IDs or URLs. Rows of all datasets go to one output dataset; with more than one dataset each row gets a \_source column with its dataset ID. Use one kind of source: datasets, a JSON URL or pasted JSON. Leave all empty for a free demo.

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

Same as Datasets to flatten, for a single dataset ID or URL (kept for existing tasks and API calls). Can be combined with the list.

## `jsonUrl` (type: `string`):

Public http(s) link to a JSON array, an object holding one array (like {"data": \[...]}) or NDJSON (one object per line), up to 500 MB.

## `items` (type: `array`):

A JSON array of objects to flatten, for example an API response you copied (up to 10,000 items).

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

Joins nested keys into one column name: . gives address.city, \_ gives address_city, \_\_ gives address__city. 1 to 5 characters. Default: a dot.

## `arrays` (type: `string`):

How a list is written into its one column. 'join' joins plain values with the join separator; lists that hold objects stay JSON text either way. Empty lists become empty cells.

## `joinSeparator` (type: `string`):

Used when Arrays is 'join'. Default: semicolon and space.

## `maxDepth` (type: `integer`):

How many levels deep to flatten. Deeper objects are kept as JSON text in one column. Default 20 (everything, in practice).

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

Optional. Flatten only the first N items, for example to try your settings on a big dataset. Empty = all rows.

## Actor input object example

```json
{
  "separator": ".",
  "arrays": "json",
  "joinSeparator": "; ",
  "maxDepth": 20
}
```

# Actor output Schema

## `rows` (type: `string`):

One flat item per input item. Download as CSV, Excel, JSON or XML from the run page or the API.

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

Record STATS: source, separator, rows written, rows charged, all column names, whether the run stopped early, and notes.

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("ucchiii/flatten-json").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 = {}

# Run the Actor and wait for it to finish
run = client.actor("ucchiii/flatten-json").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 '{}' |
apify call ucchiii/flatten-json --silent --output-dataset

```

## MCP server setup

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

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/QKsfYM1cuCMsD3wRf/builds/Q172tVldRBXfgk5mX/openapi.json
