# Data Format Converter 🔄 — JSON, YAML, TOML, CSV Tool (`perryay/data-format-converter`) Actor

Convert, validate, beautify, and minify data between JSON, YAML, TOML, and CSV formats. Supports customizable CSV delimiter, indentation, and key sorting. Batch processing up to 20 items.

- **URL**: https://apify.com/perryay/data-format-converter.md
- **Developed by:** [Perry AY](https://apify.com/perryay) (community)
- **Categories:** Developer tools
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.005 / actor start

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

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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/docs.md):

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

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python/docs.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/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

## Data Format Converter 📄 — JSON, YAML, TOML, CSV Converter & Validator

**Convert, validate, beautify, and minify structured data between JSON, YAML, TOML, and CSV formats. Batch up to 20 items, with deep syntax validation and customizable formatting — all in a single deterministic call.**

Every development team works with multiple data formats. Configuration files in YAML, API payloads in JSON, application settings in TOML, and tabular data in CSV — each format has its strengths, but moving data between them reliably is a constant source of friction. **Data Format Converter** eliminates that friction: provide any input, specify source and target format, and receive perfectly converted output with full validation, proper escaping, and format-idiomatic structure preservation.

Batch up to 20 items in a single run for bulk ETL workflows, CI/CD pipeline transformations, or configuration file migrations. Every conversion is sandboxed, size-limited, and logged transparently — no data leaves the secure Apify execution environment. Four operation modes (convert, validate, beautify, minify) with batch processing for up to 20 items.

---

### What does it do?

**Data Format Converter** accepts structured data in JSON, YAML, TOML, or CSV format and transforms it to any other supported format while preserving structural fidelity, data types, and nested relationships. The actor handles the full conversion roundtrip: parsing the source format into an internal representation, then serializing that representation into the target format using format-specific best practices (sorted keys, controlled indentation, proper quoting, and delimiter handling).

Beyond simple conversion, the actor provides **deep validation** that goes beyond basic syntax checking. For JSON inputs, it detects duplicate keys at arbitrary nesting depth, validates type consistency across arrays, and flags non-standard root types. For YAML, it detects merge keys (`<<`), tab-indentation issues, and ambiguous scalar quoting. For TOML, it validates dotted-key conflicts and table-array consistency. For CSV, it checks row-length uniformity, multi-line cell detection, and quoting correctness. Each validation run produces a structured error list with actionable messages.

The actor also supports **beautify** and **minify** modes for format-specific pretty-printing and compaction. Beautify re-serializes any format with controlled indentation, optional key sorting, and proper formatting. Minify produces the most compact possible representation — ideal for storage optimization, bandwidth reduction, or preparing data for transmission. JSON minification removes all non-essential whitespace; YAML, TOML, and CSV minification compresses indentation to zero.

### Who is it for?

| Persona | What they use it for |
|---------|----------------------|
| **Backend Developer** | Converting API response payloads between JSON and YAML for configuration files, formatting raw JSON logs for debugging, and validating incoming webhook data |
| **Data Engineer** | Transforming CSV exports into JSON or YAML for downstream processing, normalizing mixed-format data streams in ETL pipelines, and validating schema consistency across format boundaries |
| **DevOps / SRE Engineer** | Converting Kubernetes manifests, Ansible playbooks, and Terraform configs between YAML and JSON, validating TOML configuration files before deployment, and beautifying generated configs for code review |
| **QA Engineer** | Validating API response formats against expected structures, minifying test fixtures for storage efficiency, and converting test data between formats for cross-platform test suites |
| **API Integrator** | Transforming third-party API responses from JSON to YAML for internal documentation, converting CSV spreadsheets to JSON for programmatic consumption, and validating TOML configuration files for SDK integration |
| **Technical Writer** | Generating pretty-printed code samples in multiple formats for documentation, converting data examples between JSON and YAML for multi-format tutorials, and validating example data correctness |
| **Security Analyst** | Scanning YAML configuration files for duplicate key overrides, validating JSON payloads for structural integrity before security scanning, and converting CSV threat intel feeds to structured formats |

### Why use this?

- **Four formats, one tool.** Most converters handle JSON-to-YAML or JSON-to-CSV in isolation. This actor covers all four format pairs — JSON, YAML, TOML, and CSV — in every combination. No more installing separate libraries or maintaining bespoke conversion scripts for each pair.

- **Four operation modes, not just conversion.** Beyond `convert`, the actor offers `validate` (deep structural analysis with actionable error messages), `beautify` (consistent pretty-printing with controlled indentation), and `minify` (compact output for storage and transmission). One actor replaces an entire toolbox.

- **Deep validation catches what syntax checkers miss.** Standard parsers tell you whether data is syntactically valid. This actor also detects duplicate JSON keys at any nesting depth, YAML merge-key overrides, TOML dotted-key conflicts, CSV row-length inconsistencies, and tab-indentation in YAML. These are real-world issues that cause silent data corruption in production pipelines.

- **Batch processing with independent error isolation.** Process up to 20 items in a single run. Each item is processed independently — one invalid document never blocks the rest. Perfect for bulk ETL, configuration file migrations, and regression test suites where you need to convert or validate dozens of files at once.

- **Deterministic, idempotent output.** Given the same input and parameters, the actor always produces identical output. No randomness, no server-side state, no hidden transformations. This matters for CI/CD pipelines, regression testing, and any workflow where repeatability is a requirement.

- **Zero external dependencies, no data leakage.** The actor runs entirely inside Apify's secure execution container with no outbound HTTP calls. Your data is parsed, converted, and returned — it is never stored, logged, or transmitted to any third party. Sensitive configuration files and proprietary data remain fully under your control.

### Features

1. **Multi-format bidirectional conversion** — Convert between any pair of JSON, YAML (1.2), TOML (v1.0), and CSV formats. All 12 directed conversion paths are supported (4 formats × 3 targets each). Nested structures, arrays, and mixed types are preserved with format-appropriate serialization.

2. **Deep syntax validation with structured errors** — Go beyond basic parse success/failure. The validator checks duplicate JSON keys at arbitrary depth, YAML merge-key conflicts, tab-indentation violations, TOML dotted-key collisions, and CSV row-length consistency. Each error includes a human-readable message you can act on immediately.

3. **Controlled pretty-printing (beautify mode)** — Re-serialize any format with configurable indentation (0–16 spaces) and optional alphabetical key sorting. JSON output uses strict ECMA-404 formatting. YAML output uses block-scalar style with proper string quoting to prevent type coercion. TOML output uses canonical table ordering.

4. **Compact minification (minify mode)** — JSON minification produces the smallest possible representation (no whitespace, compressed separators). For YAML, TOML, and CSV, minification removes unnecessary indentation while preserving structural validity. Ideal for reducing storage costs and optimizing API payload sizes.

5. **CSV with configurable delimiters and headers** — Parse and generate CSV with custom delimiters (comma, semicolon, tab, pipe, or any single character). Toggle header row inclusion. Dict-based rows preserve key ordering. Multi-line cells are detected during validation. Export structured data to CSV for spreadsheet analysis or import CSV data into structured formats for programmatic processing.

6. **Batch mode with independent item processing** — Submit up to 20 items in the `batchData` array. Each item specifies its own `inputData`, `sourceFormat`, and `targetFormat`. Items are processed sequentially with independent error handling — a failure in one item never cancels the others. Every result includes its own success status, parse time, and validation errors.

7. **Key sorting for consistent output** — Enable `sortKeys` to produce alphabetically sorted object keys in JSON and YAML output. This is critical for diff-friendly output, reproducible builds, and configuration management where key ordering must be deterministic across runs.

8. **Input size guarding and preview** — All inputs are limited to 1 MB per item, preventing resource exhaustion from oversized documents. Every result includes an `inputPreview` field showing the first 200 characters, making it easy to identify which input produced which output in batch results.

9. **Millisecond performance metrics** — Every result includes `parseTimeMs`, giving you precise insight into processing duration. Individual conversions typically complete in under 50 ms for documents under 100 KB, making the actor suitable for latency-sensitive workflows.

10. **Charge events for transparent billing** — Four distinct charge events (`apify-actor-start`, `format-convert`, `batch-convert`, `deep-validate`) provide granular visibility into usage costs. The `charge_safe` wrapper ensures a charge failure never aborts a successful conversion.

### Input Parameters

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `inputData` | string | Yes* | — | The data source to convert, validate, beautify, or minify. Provide the raw string content in the format specified by `sourceFormat`. Maximum length: 1,000,000 characters. |
| `sourceFormat` | string | Yes | `json` | Format of the input data. One of: `json`, `yaml`, `toml`, `csv`. |
| `targetFormat` | string | Yes** | `yaml` | Target format for conversion. One of: `json`, `yaml`, `toml`, `csv`. Only used when `mode` is `convert`. |
| `mode` | string | No | `convert` | Operation mode. One of: `convert`, `validate`, `beautify`, `minify`. |
| `batchData` | array | No*** | `[]` | Array of batch items for processing multiple inputs in one run. Each item supports `inputData`, `sourceFormat`, `targetFormat`. Maximum 20 items. |
| `batchMode` | boolean | No | `false` | Enable batch processing. When `true`, provide items in `batchData` instead of using `inputData`. |
| `csvDelimiter` | string | No | `,` | Delimiter character for CSV parsing and generation. Common values: `,` (comma), `;` (semicolon), `\t` (tab), `|` (pipe). |
| `csvHasHeader` | boolean | No | `true` | Whether the CSV data includes a header row. When `true`, the first row becomes dictionary keys. |
| `indentSize` | integer | No | `2` | Number of spaces for indentation in pretty-printed output (0–16). Applied to JSON and YAML. |
| `sortKeys` | boolean | No | `false` | Sort object keys alphabetically in JSON and YAML output. |

> *Either use `inputData` for single mode, or enable `batchMode` with `batchData` for batch processing.\
> **Required when `mode` is `convert`. Ignored for `validate`, `beautify`, and `minify` modes.\
> ***Required when `batchMode` is `true`. At least one item with non-empty `inputData` is needed.

### Example Input

#### Convert JSON to YAML

```json
{
  "inputData": "{\"name\": \"Acme Corp\", \"version\": 2, \"active\": true, \"tags\": [\"production\", \"us-east\"], \"config\": {\"timeout\": 30, \"retries\": 3}}",
  "sourceFormat": "json",
  "targetFormat": "yaml",
  "mode": "convert",
  "indentSize": 2,
  "sortKeys": false
}
````

#### Validate a YAML document

```json
{
  "inputData": "name: Acme Corp\nversion: 2\nactive: true\ntags:\n  - production\n  - us-east\n",
  "sourceFormat": "yaml",
  "mode": "validate"
}
```

#### Beautify a minified JSON string

```json
{
  "inputData": "{\"name\":\"Acme Corp\",\"version\":2,\"nested\":{\"key\":\"value\",\"list\":[1,2,3]}}",
  "sourceFormat": "json",
  "mode": "beautify",
  "indentSize": 4,
  "sortKeys": true
}
```

#### Minify a JSON string

```json
{
  "inputData": "{\n  \"name\": \"Acme Corp\",\n  \"version\": 2\n}",
  "sourceFormat": "json",
  "mode": "minify"
}
```

#### Convert CSV to JSON

```json
{
  "inputData": "name,version,active\nAcme Corp,2,true\nExample Inc,1,false\n",
  "sourceFormat": "csv",
  "targetFormat": "json",
  "mode": "convert",
  "csvDelimiter": ",",
  "csvHasHeader": true
}
```

#### Batch mode — multiple conversions in one run

```json
{
  "batchMode": true,
  "batchData": [
    {
      "inputData": "{\"id\": 1, \"name\": \"Alpha\"}",
      "sourceFormat": "json",
      "targetFormat": "yaml"
    },
    {
      "inputData": "key: value\nnested:\n  a: 1\n  b: 2\n",
      "sourceFormat": "yaml",
      "targetFormat": "toml"
    },
    {
      "inputData": "name,role\nAlice,Developer\nBob,Tester\n",
      "sourceFormat": "csv",
      "targetFormat": "json"
    }
  ],
  "mode": "convert",
  "indentSize": 2
}
```

### Output Format

#### Result fields

| Field | Type | Description |
|-------|------|-------------|
| `id` | integer | Sequential item identifier (0-indexed). Always `0` for single mode. |
| `sourceFormat` | string | Original format of the input data, as specified or inferred. |
| `targetFormat` | string | Target format after conversion. Same as `sourceFormat` for validate/beautify/minify modes. |
| `mode` | string | Operation performed: `convert`, `validate`, `beautify`, or `minify`. |
| `inputPreview` | string | First 200 characters of the original input for identification. |
| `result` | string | Converted, validated, beautified, or minified output. For validate mode, shows a summary or the prettified representation. |
| `resultLength` | integer | Character count of the `result` string. |
| `isValid` | boolean | Whether the input passed validation. Always `true` for non-validate modes unless an error occurred. |
| `validationErrors` | array of string | List of validation error messages. Empty array when input is valid. |
| `parseTimeMs` | number | Processing duration in milliseconds (rounded to 1 decimal place). |
| `error` | string or null | Error message if processing failed. `null` on success. |
| `success` | boolean | `true` when the operation completed without errors. |

#### Single convert result (JSON → YAML)

```json
{
  "id": 0,
  "sourceFormat": "json",
  "targetFormat": "yaml",
  "mode": "convert",
  "inputPreview": "{\"name\": \"Acme Corp\", \"version\": 2, \"active\": true, \"tags\": [\"production\", \"us-east\"], \"config\": {\"timeout\": 30, \"retries\": 3}}",
  "result": "name: Acme Corp\nversion: 2\nactive: true\ntags:\n  - production\n  - us-east\nconfig:\n  timeout: 30\n  retries: 3\n",
  "resultLength": 105,
  "isValid": true,
  "validationErrors": [],
  "parseTimeMs": 12.3,
  "error": null,
  "success": true
}
```

#### Validation result with errors

```json
{
  "id": 0,
  "sourceFormat": "json",
  "targetFormat": "json",
  "mode": "validate",
  "inputPreview": "{\"name\": \"Acme Corp\", \"version\": 2, \"name\": \"Duplicate\"}",
  "result": "",
  "resultLength": 0,
  "isValid": false,
  "validationErrors": [
    "Duplicate JSON key: 'name'"
  ],
  "parseTimeMs": 3.2,
  "error": null,
  "success": true
}
```

#### Batch result (2 items)

```json
{
  "id": 0,
  "sourceFormat": "json",
  "targetFormat": "yaml",
  "mode": "convert",
  "inputPreview": "{\"id\": 1, \"name\": \"Alpha\"}",
  "result": "id: 1\nname: Alpha\n",
  "resultLength": 17,
  "isValid": true,
  "validationErrors": [],
  "parseTimeMs": 8.7,
  "error": null,
  "success": true
}
```

Followed by the second item. Each batch item is pushed as a separate dataset entry for independent consumption.

### Use Cases

- **Configuration file migration** — Convert a fleet of YAML configuration files to TOML or JSON when migrating between infrastructure tooling (e.g., Ansible to Terraform, Docker Compose to Kubernetes). Validate every converted file before deployment to catch structural issues early.

- **API response transformation** — Receive JSON from a third-party API, convert it to YAML for internal documentation, or flatten nested JSON structures into CSV for business intelligence reporting. The actor handles type conversion and nested structure mapping automatically.

- **CI/CD pipeline data formatting** — Integrate into build pipelines to format, validate, or minify configuration files before deployment. Use beautify mode to enforce consistent formatting standards across your codebase. Use minify mode to reduce artifact sizes.

- **Spreadsheet-to-structured-data ingestion** — Parse CSV exports from Google Sheets, Excel, or Airtable and convert them to JSON or YAML for programmatic consumption. Configure custom delimiters for non-standard CSV formats (semicolon-separated, tab-separated).

- **Multi-format data normalization** — Ingest data from multiple sources that each use different formats, normalize everything to a single target format, and validate consistency across sources. Batch mode processes all conversions in one run with independent error handling per source.

- **Security auditing of configuration files** — Use validate mode to scan YAML and TOML configuration files for duplicate keys, merge-key overrides, or other structural anomalies that could indicate misconfiguration or malicious injection. Detect tab-indentation issues before they cause parser failures in production.

- **Documentation code sample generation** — Generate consistent, properly-formatted code samples in JSON, YAML, and TOML for API documentation and developer guides. Use beautify mode with sorted keys to produce examples that are both readable and deterministic.

- **ETL data pipeline intermediate transformation** — As part of a larger data processing pipeline, use the actor to transform data between formats at intermediate stages. The deterministic output ensures repeatable ETL runs, and the millisecond timing metrics help track pipeline performance.

### FAQ

**1. What formats are supported for conversion?**
JSON (ECMA-404), YAML (1.2 with SafeLoader), TOML (v1.0 via tomllib), and CSV (RFC 4180 with configurable delimiters). All 12 directed conversion paths between these four formats are supported.

**2. What is the maximum input size?**
Each item is limited to 1,000,000 characters. For batch mode, up to 20 items are supported per run. Inputs exceeding the size limit will trigger a validation error.

**3. Does the actor make any external API calls?**
No. The actor is entirely self-contained. All parsing, conversion, and validation runs locally inside the Apify execution container. There are zero outbound HTTP calls — your data is never sent to any external service.

**4. How are CSV files with custom delimiters handled?**
Use the `csvDelimiter` parameter to specify any single character delimiter. Common choices include comma (`,`), semicolon (`;`), tab (`\t`), and pipe (`|`). The `csvHasHeader` parameter controls whether the first row is treated as column names.

**5. What happens if conversion fails for one item in batch mode?**
Each batch item is processed independently. A failure in one item produces an error result for that item only — all other items are processed normally. Every result includes a `success` boolean and an `error` string for individual status checking.

**6. Does the actor handle deeply nested JSON objects?**
Yes. The parser handles arbitrary nesting depth within available memory limits. Nested objects and arrays are preserved during conversion with format-appropriate serialization (YAML block-nesting, TOML table arrays, CSV flattened representation).

**7. What does validate mode check beyond basic syntax?**
Validate mode performs deep structural analysis: duplicate JSON keys at any nesting depth, YAML merge-key conflicts, tab-indentation in YAML, TOML dotted-key collisions, CSV row-length consistency, multi-line cell detection, encoding validation, and type consistency warnings.

**8. Can I sort object keys in the output?**
Yes. Set `sortKeys: true` to produce alphabetically sorted object keys in JSON and YAML output. This is useful for diff-friendly, deterministic output across repeated runs. TOML and CSV output ordering is determined by the input structure.

**9. What is the difference between beautify and minify modes?**
Beautify re-serializes data with controlled indentation (configurable via `indentSize`) and optional key sorting. Minify produces the most compact representation — JSON output has no whitespace, YAML/TOML/CSV output uses zero indentation. Both modes validate the input first.

**10. Is the actor suitable for use in CI/CD pipelines?**
Yes. The actor is fully callable via the Apify API, returns deterministic output, has configurable timeouts (default 300s, configurable up to the platform limit), and uses charge-safe billing that never aborts on charge failure. The structured output with success flags and parse-time metrics makes it straightforward to integrate into automated workflows.

**11. How is TOML serialization handled?**
TOML output uses the tomli\_w library for standards-compliant serialization following the TOML v1.0 specification. Tables are serialized in key-insertion order, arrays of tables use the `[[array]]` syntax, and inline tables are used where appropriate. Non-dictionary root values are wrapped in a `value` key.

**12. What happens if my CSV data has inconsistent row lengths?**
The validator detects and reports row-length inconsistencies. During conversion, missing values are rendered as empty strings and extra values are appended. The `csvHasHeader` parameter controls whether the first row defines column names — without it, auto-generated keys (`col_0`, `col_1`, etc.) are used.

### Usage & Billing

This actor uses event-based billing with four charge events. Each event is charged only when the corresponding operation occurs. The `charge_safe` wrapper ensures that a charge failure never aborts your conversion — results are always returned.

| Event | Price | Trigger |
|-------|-------|---------|
| `apify-actor-start` | $0.005 | Charged once at the start of every actor run |
| `format-convert` | $0.01 | Charged per successful single conversion (mode: `convert`) |
| `batch-convert` | $0.008 | Charged per batch item processed (mode: `convert` with `batchMode: true`) |
| `deep-validate` | $0.005 | Charged per successful validation run (mode: `validate`) |

**Cost examples:**

- **Single conversion** (JSON → YAML): 1 × `apify-actor-start` ($0.005) + 1 × `format-convert` ($0.01) = **$0.015**
- **Single validation** (YAML document): 1 × `apify-actor-start` ($0.005) + 1 × `deep-validate` ($0.005) = **$0.01**
- **Batch of 10 conversions**: 1 × `apify-actor-start` ($0.005) + 10 × `batch-convert` ($0.008) = **$0.085**
- **Beautify or minify**: 1 × `apify-actor-start` ($0.005) — beautify and minify modes do not trigger format-convert or validate charges

Platform-level Apify compute and storage charges apply separately based on your Apify plan. See the [Apify pricing page](https://apify.com/pricing) for current platform rates.

### MCP Integration

Use this actor directly from MCP-compatible environments such as Claude Code, Cursor, or any tool with the Apify MCP server configured.

#### Single conversion via MCP

```json
{
  "input": {
    "inputData": "{\"name\": \"Acme Corp\", \"version\": 2}",
    "sourceFormat": "json",
    "targetFormat": "yaml",
    "mode": "convert"
  }
}
```

#### Batch validation via MCP

```json
{
  "input": {
    "batchMode": true,
    "batchData": [
      {
        "inputData": "{\"id\": 1, \"status\": \"active\"}",
        "sourceFormat": "json",
        "targetFormat": "yaml"
      },
      {
        "inputData": "name: Test\nversion: 1.0\n",
        "sourceFormat": "yaml",
        "targetFormat": "json"
      }
    ],
    "mode": "convert"
  }
}
```

#### MCP Integration

This actor can be used as a tool inside any MCP-compatible AI client (Claude Desktop, Cursor, VS Code with Copilot) via the Apify MCP server.

#### Quick Start

1. Ensure your MCP client is configured to use the Apify MCP server:

```json
{
  "mcpServers": {
    "apify": {
      "url": "https://mcp.apify.com"
    }
  }
}
```

On first connection, your browser will open to sign in to Apify and authorize access.

2. Ask your AI assistant to convert data between formats. Example prompts:

> "Convert this JSON to YAML: {"name": "Acme Corp", "version": 2, "active": true}"

> "Validate the following TOML file for syntax errors: \[server]\nhost = "localhost"\nhost = "example.com""

#### Bearer Token Alternative

For headless environments (CI/CD, VS Code without browser-based OAuth), configure with a personal API token:

```json
{
  "mcpServers": {
    "apify": {
      "url": "https://mcp.apify.com",
      "headers": {
        "Authorization": "Bearer YOUR_APIFY_TOKEN"
      }
    }
  }
}
```

> **Note:** The OAuth flow is recommended for security. API tokens should be treated as secrets and never committed to version control.

### Related Tools

- [JSON Studio](https://apify.com/perryay/json-studio) — Format, validate, diff, transform, and explore JSON documents with 8 operation modes
- [Regex Lab](https://apify.com/perryay/regex-lab) — Design, test, and debug regular expressions with visual matching and batch processing
- [Diff Tool](https://apify.com/perryay/diff-tool-compare-two-texts-urls) — Compare two texts, URLs, or files for differences with structured output
- [Mock Data Generator](https://apify.com/perryay/mock-data-generator) — Generate realistic mock data in JSON, CSV, and SQL formats for testing and development
- [SQL Formatter & Query Analyzer](https://apify.com/perryay/sql-formatter-query-analyzer) — Format, validate, and analyze SQL queries with execution plan insights

# Actor input Schema

## `inputData` (type: `string`):

The data source to convert, validate, beautify, or minify. Provide raw string content for the specified sourceFormat.

## `sourceFormat` (type: `string`):

Format of the input data. Required for convert and validate modes.

## `targetFormat` (type: `string`):

Target format for conversion. Required when mode is convert. Ignored for validate/beautify/minify.

## `mode` (type: `string`):

What operation to perform on the input data.

## `batchData` (type: `array`):

Array of batch items for processing multiple conversions in one run. Each item has inputData, sourceFormat, targetFormat. Used when batchMode is true.

## `batchMode` (type: `boolean`):

Enable batch processing. When true, provide an array of items in batchData. Each item is processed independently.

## `csvDelimiter` (type: `string`):

Delimiter character for CSV parsing and generation. Common values: comma (,), semicolon (;), tab (\t), pipe (|).

## `csvHasHeader` (type: `boolean`):

Whether the CSV data includes a header row. When true, the first row is used as keys. When false, auto-generated keys (col\_0, col\_1, ...) are used.

## `indentSize` (type: `number`):

Number of spaces for indentation in pretty-printed output. Applied to JSON and YAML outputs. Set to 0 for no extra indentation.

## `sortKeys` (type: `boolean`):

Sort object keys alphabetically in the output. Applies to JSON and YAML target formats.

## Actor input object example

```json
{
  "inputData": "{\"key\": \"value\"}",
  "sourceFormat": "json",
  "targetFormat": "yaml",
  "mode": "convert",
  "batchData": [
    {
      "inputData": "{\"id\": 1}",
      "sourceFormat": "json",
      "targetFormat": "yaml"
    },
    {
      "inputData": "key: value\nnested:\n  a: 1",
      "sourceFormat": "yaml",
      "targetFormat": "json"
    }
  ],
  "batchMode": false,
  "csvDelimiter": ",",
  "csvHasHeader": true,
  "indentSize": 2,
  "sortKeys": false
}
```

# Actor output Schema

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

Per-item conversion results in the default dataset

# 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 = {
    "inputData": "{\"key\": \"value\"}",
    "batchData": [
        {
            "inputData": "{\"id\": 1}",
            "sourceFormat": "json",
            "targetFormat": "yaml"
        },
        {
            "inputData": "key: value\nnested:\n  a: 1",
            "sourceFormat": "yaml",
            "targetFormat": "json"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("perryay/data-format-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 = {
    "inputData": "{\"key\": \"value\"}",
    "batchData": [
        {
            "inputData": "{\"id\": 1}",
            "sourceFormat": "json",
            "targetFormat": "yaml",
        },
        {
            "inputData": """key: value
nested:
  a: 1""",
            "sourceFormat": "yaml",
            "targetFormat": "json",
        },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("perryay/data-format-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 '{
  "inputData": "{\\"key\\": \\"value\\"}",
  "batchData": [
    {
      "inputData": "{\\"id\\": 1}",
      "sourceFormat": "json",
      "targetFormat": "yaml"
    },
    {
      "inputData": "key: value\\nnested:\\n  a: 1",
      "sourceFormat": "yaml",
      "targetFormat": "json"
    }
  ]
}' |
apify call perryay/data-format-converter --silent --output-dataset

```

## MCP server setup

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

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "Data Format Converter 🔄 — JSON, YAML, TOML, CSV Tool",
        "description": "Convert, validate, beautify, and minify data between JSON, YAML, TOML, and CSV formats. Supports customizable CSV delimiter, indentation, and key sorting. Batch processing up to 20 items.",
        "version": "1.0",
        "x-build-id": "xoGhLpMwe3vQwDbSh"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/perryay~data-format-converter/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-perryay-data-format-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/perryay~data-format-converter/runs": {
            "post": {
                "operationId": "runs-sync-perryay-data-format-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/perryay~data-format-converter/run-sync": {
            "post": {
                "operationId": "run-sync-perryay-data-format-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": {
                    "inputData": {
                        "title": "Input Data",
                        "type": "string",
                        "description": "The data source to convert, validate, beautify, or minify. Provide raw string content for the specified sourceFormat."
                    },
                    "sourceFormat": {
                        "title": "Source Format",
                        "enum": [
                            "json",
                            "yaml",
                            "toml",
                            "csv"
                        ],
                        "type": "string",
                        "description": "Format of the input data. Required for convert and validate modes.",
                        "default": "json"
                    },
                    "targetFormat": {
                        "title": "Target Format",
                        "enum": [
                            "json",
                            "yaml",
                            "toml",
                            "csv"
                        ],
                        "type": "string",
                        "description": "Target format for conversion. Required when mode is convert. Ignored for validate/beautify/minify.",
                        "default": "yaml"
                    },
                    "mode": {
                        "title": "Operation Mode",
                        "enum": [
                            "convert",
                            "validate",
                            "beautify",
                            "minify"
                        ],
                        "type": "string",
                        "description": "What operation to perform on the input data.",
                        "default": "convert"
                    },
                    "batchData": {
                        "title": "Batch Data",
                        "type": "array",
                        "description": "Array of batch items for processing multiple conversions in one run. Each item has inputData, sourceFormat, targetFormat. Used when batchMode is true.",
                        "default": []
                    },
                    "batchMode": {
                        "title": "Batch Mode",
                        "type": "boolean",
                        "description": "Enable batch processing. When true, provide an array of items in batchData. Each item is processed independently.",
                        "default": false
                    },
                    "csvDelimiter": {
                        "title": "CSV Delimiter",
                        "type": "string",
                        "description": "Delimiter character for CSV parsing and generation. Common values: comma (,), semicolon (;), tab (\\t), pipe (|).",
                        "default": ","
                    },
                    "csvHasHeader": {
                        "title": "CSV Has Header Row",
                        "type": "boolean",
                        "description": "Whether the CSV data includes a header row. When true, the first row is used as keys. When false, auto-generated keys (col_0, col_1, ...) are used.",
                        "default": true
                    },
                    "indentSize": {
                        "title": "Indent Size",
                        "minimum": 0,
                        "maximum": 16,
                        "type": "number",
                        "description": "Number of spaces for indentation in pretty-printed output. Applied to JSON and YAML outputs. Set to 0 for no extra indentation.",
                        "default": 2
                    },
                    "sortKeys": {
                        "title": "Sort Keys",
                        "type": "boolean",
                        "description": "Sort object keys alphabetically in the output. Applies to JSON and YAML target formats.",
                        "default": false
                    }
                }
            },
            "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
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
