# JSON to CSV Converter — Flatten Nested Data (`junipr/json-to-csv-converter`) Actor

Convert JSON arrays, objects, API responses, and nested data into CSV or TSV with flattening, field selection, and file exports.

- **URL**: https://apify.com/junipr/json-to-csv-converter.md
- **Developed by:** [junipr](https://apify.com/junipr) (community)
- **Categories:** Developer tools, Automation
- **Stats:** 2 total users, 1 monthly users, 50.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.95 / 1,000 row converteds

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/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/platform/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## JSON to CSV Converter — Flatten Nested Data

### What does JSON to CSV Converter do?

JSON to CSV Converter transforms JSON data into CSV or TSV format. It accepts input from three sources: direct JSON input, a URL pointing to a JSON endpoint, or an Apify dataset ID. The actor automatically flattens nested objects using dot notation, joins arrays into comma-separated values, handles null values, and produces a properly escaped CSV file with configurable column delimiters.

The converted output is saved both as individual rows in the default dataset and as a complete file in the key-value store under the `OUTPUT` key. This means you can download the full CSV file directly or access individual rows through the Apify API.

### Features

- **Three data sources** — paste JSON directly, fetch from a URL, or pull from an Apify dataset by ID
- **CSV and TSV output** — choose comma-separated or tab-separated format, or set a custom delimiter
- **Automatic nested flattening** — nested objects become dot-notation columns (e.g., `address.city`)
- **Field selection** — include only specific fields or exclude unwanted fields from the output
- **Array handling** — arrays are joined with comma separators into a single cell value
- **Null value replacement** — configure what empty/null values display as in the output
- **Header control** — optionally exclude the header row for append workflows
- **Row limits** — cap output at a maximum number of rows (up to 10,000 per run)
- **Proper CSV escaping** — handles quotes, newlines, and delimiters within cell values
- **Pay-per-row pricing** — only pay for rows successfully converted

### Input Configuration

```json
{
  "jsonData": "[{\"id\":1,\"name\":\"Alpha\"}]",
  "jsonUrl": "",
  "datasetId": "",
  "outputFormat": "csv",
  "flattenNested": true,
  "delimiter": ",",
  "includeHeaders": true,
  "fields": [],
  "excludeFields": [],
  "maxRows": 1,
  "nullValue": ""
}
````

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `jsonData` | string | one-record JSON array | Direct JSON string to convert. Takes priority over other sources. |
| `jsonUrl` | string | `""` | URL to fetch JSON data from |
| `datasetId` | string | `""` | Apify dataset ID to pull items from |
| `outputFormat` | string | `"csv"` | Output format: `csv` or `tsv` |
| `flattenNested` | boolean | `true` | Flatten nested objects using dot notation |
| `delimiter` | string | `","` | Column separator character. Defaults to comma for CSV, tab for TSV. |
| `includeHeaders` | boolean | `true` | Include column headers as the first row |
| `fields` | string\[] | `[]` | Only include these fields (empty = all fields) |
| `excludeFields` | string\[] | `[]` | Exclude these fields from output |
| `maxRows` | integer | `1` | Maximum rows to output (max 10,000) |
| `nullValue` | string | `""` | Replacement string for null/undefined/missing values |

### Output Format

Each row is saved as a dataset item containing the row number, the flattened data, and the formatted CSV line:

```json
{
  "rowNumber": 1,
  "data": {
    "body": "This is the post body text...",
    "id": "1",
    "title": "Converted Record",
    "userId": "1"
  },
  "csvLine": "\"This is the post body text...\",\"1\",\"Converted Record\",\"1\""
}
```

The complete CSV/TSV file for successfully charged dataset rows is also saved under the KVS key `OUTPUT`. Empty sources and billing stops produce an uncharged diagnostic instead of an unbilled output file.

### Usage Examples / Use Cases

- **Apify pipeline chaining** — convert output from any Apify scraper to CSV by passing its dataset ID as input
- **API data export** — fetch JSON from any REST API endpoint and convert to a spreadsheet-friendly format
- **Data transformation** — flatten deeply nested JSON structures into flat tabular data for analysis
- **Report generation** — produce CSV exports from JSON data sources for business reporting
- **ETL workflows** — use as a transformation step between JSON data sources and database imports
- **Spreadsheet import** — prepare JSON data for import into Google Sheets, Excel, or other spreadsheet tools

### Ready-to-run public tasks

- **Convert one API record** — fetches one public JSON record and stores headered CSV.
- **Flatten a nested record** — demonstrates dot-path columns from one inline object.
- **Export selected TSV fields** — selects two fields and writes tab-separated output.

Every task caps conversion at one row and demonstrates a distinct source or output behavior.

### Pricing

This actor uses Pay-Per-Event (PPE) pricing: **$1.95 per 1,000 rows converted** ($0.00195 per `row-converted` event). Apify platform usage follows the live Store pricing entry.

### FAQ

#### Can I convert output from another Apify actor?

Yes. Run any Apify actor, copy its dataset ID from the run results, and paste it into the `datasetId` field. The converter will fetch all items from that dataset and produce a CSV file. This is the easiest way to get CSV output from any scraper.

#### How does nested object flattening work?

When `flattenNested` is enabled (default), nested objects are flattened using dot notation. For example, `{"address": {"city": "Chicago", "zip": "60601"}}` becomes two columns: `address.city` and `address.zip`. Arrays are joined into a single string with comma separators. Set `flattenNested` to false to keep nested objects as JSON strings in cells.

#### What happens with inconsistent JSON records?

The converter collects all unique field names across all records. If a record is missing a field that other records have, the cell is filled with the `nullValue` setting (empty string by default). Columns are sorted alphabetically for consistent output.

#### Where is the output file stored?

The complete CSV/TSV file is saved in the run's key-value store under the key `OUTPUT`. You can download it from the Apify Console or through the default key-value-store record endpoint. Individual paid rows are also available in the default dataset.

#### Does this actor need a proxy?

No. JSON to CSV Converter is a data transformation tool that does not scrape websites. It works on any Apify plan including the free tier without any proxy configuration.

### Related Actors

- [Google News Scraper](https://apify.com/junipr/google-news-scraper) — scrape news articles and convert results to CSV
- [Etsy Product Scraper](https://apify.com/junipr/etsy-product-scraper) — scrape Etsy products and export as CSV
- [Reddit Scraper](https://apify.com/junipr/reddit-scraper) — scrape Reddit posts and comments for analysis
- [Hacker News Scraper](https://apify.com/junipr/hacker-news-scraper) — extract Hacker News stories and export to CSV
- [Markdown to HTML Converter](https://apify.com/junipr/markdown-to-html) — convert Markdown documents to styled HTML

# Actor input Schema

## `jsonData` (type: `string`):

Direct JSON input as a string or object. Can be an array of objects or a single object. Leave empty to use jsonUrl or datasetId instead.

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

URL to fetch JSON data from. The response must be valid JSON (array of objects or single object).

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

Apify dataset ID to fetch items from and convert. Takes precedence over jsonUrl if both are provided.

## `outputFormat` (type: `string`):

Output file format: csv (comma-separated) or tsv (tab-separated).

## `flattenNested` (type: `boolean`):

Flatten nested objects using dot notation (e.g., {a: {b: 1}} becomes a.b column). Arrays are joined with comma separator.

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

Character used to separate columns. Defaults to comma for CSV, tab for TSV. Override for custom delimiters like semicolon or pipe.

## `includeHeaders` (type: `boolean`):

Include column headers as the first row of the output.

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

Specific field names to include in the output. Leave empty to include all fields. Supports dot notation for nested fields (e.g., 'address.city').

## `excludeFields` (type: `array`):

Field names to exclude from the output. Applied after field inclusion. Supports dot notation for nested fields.

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

Maximum number of rows to include in the output. Capped at 10,000 to keep runs predictable and avoid runaway billing.

## `nullValue` (type: `string`):

String to use for null, undefined, or missing values in the output.

## Actor input object example

```json
{
  "jsonData": "[{\"id\":1,\"name\":\"Alpha\"}]",
  "jsonUrl": "",
  "datasetId": "",
  "outputFormat": "csv",
  "flattenNested": true,
  "delimiter": ",",
  "includeHeaders": true,
  "fields": [],
  "excludeFields": [],
  "maxRows": 1,
  "nullValue": ""
}
```

# Actor output Schema

## `csvFile` (type: `string`):

The converted file stored in the default key-value store as OUTPUT.csv or OUTPUT.tsv.

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

Each converted row as a dataset item for API access.

# 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("junipr/json-to-csv-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 = {}

# Run the Actor and wait for it to finish
run = client.actor("junipr/json-to-csv-converter").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).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 junipr/json-to-csv-converter --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=junipr/json-to-csv-converter",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "JSON to CSV Converter — Flatten Nested Data",
        "description": "Convert JSON arrays, objects, API responses, and nested data into CSV or TSV with flattening, field selection, and file exports.",
        "version": "1.0",
        "x-build-id": "x1GMt1R33x24mwmwu"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/junipr~json-to-csv-converter/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-junipr-json-to-csv-converter",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/junipr~json-to-csv-converter/runs": {
            "post": {
                "operationId": "runs-sync-junipr-json-to-csv-converter",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/junipr~json-to-csv-converter/run-sync": {
            "post": {
                "operationId": "run-sync-junipr-json-to-csv-converter",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "properties": {
                    "jsonData": {
                        "title": "JSON Data",
                        "type": "string",
                        "description": "Direct JSON input as a string or object. Can be an array of objects or a single object. Leave empty to use jsonUrl or datasetId instead.",
                        "default": "[{\"id\":1,\"name\":\"Alpha\"}]"
                    },
                    "jsonUrl": {
                        "title": "JSON URL",
                        "type": "string",
                        "description": "URL to fetch JSON data from. The response must be valid JSON (array of objects or single object).",
                        "default": ""
                    },
                    "datasetId": {
                        "title": "Apify Dataset ID",
                        "type": "string",
                        "description": "Apify dataset ID to fetch items from and convert. Takes precedence over jsonUrl if both are provided.",
                        "default": ""
                    },
                    "outputFormat": {
                        "title": "Output Format",
                        "enum": [
                            "csv",
                            "tsv"
                        ],
                        "type": "string",
                        "description": "Output file format: csv (comma-separated) or tsv (tab-separated).",
                        "default": "csv"
                    },
                    "flattenNested": {
                        "title": "Flatten Nested Objects",
                        "type": "boolean",
                        "description": "Flatten nested objects using dot notation (e.g., {a: {b: 1}} becomes a.b column). Arrays are joined with comma separator.",
                        "default": true
                    },
                    "delimiter": {
                        "title": "Column Delimiter",
                        "type": "string",
                        "description": "Character used to separate columns. Defaults to comma for CSV, tab for TSV. Override for custom delimiters like semicolon or pipe.",
                        "default": ","
                    },
                    "includeHeaders": {
                        "title": "Include Headers",
                        "type": "boolean",
                        "description": "Include column headers as the first row of the output.",
                        "default": true
                    },
                    "fields": {
                        "title": "Include Fields",
                        "type": "array",
                        "description": "Specific field names to include in the output. Leave empty to include all fields. Supports dot notation for nested fields (e.g., 'address.city').",
                        "items": {
                            "type": "string"
                        },
                        "default": []
                    },
                    "excludeFields": {
                        "title": "Exclude Fields",
                        "type": "array",
                        "description": "Field names to exclude from the output. Applied after field inclusion. Supports dot notation for nested fields.",
                        "items": {
                            "type": "string"
                        },
                        "default": []
                    },
                    "maxRows": {
                        "title": "Maximum Rows",
                        "minimum": 1,
                        "maximum": 10000,
                        "type": "integer",
                        "description": "Maximum number of rows to include in the output. Capped at 10,000 to keep runs predictable and avoid runaway billing.",
                        "default": 1
                    },
                    "nullValue": {
                        "title": "Null Value Replacement",
                        "type": "string",
                        "description": "String to use for null, undefined, or missing values in the output.",
                        "default": ""
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
