# Structured Data Fixer — repair & normalize messy JSON/CSV/text (`pacific_waterside/structured-data-fixer`) Actor

Repair LLM-broken JSON, strip invisible characters, dedupe rows, coerce types and validate against a JSON Schema. Deterministic rules only, no API keys, no external packages.

- **URL**: https://apify.com/pacific_waterside/structured-data-fixer.md
- **Developed by:** [byd666](https://apify.com/pacific_waterside) (community)
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## 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

## Structured Data Fixer

Repair and normalize messy JSON, CSV, and plain text in one pass. **Deterministic rules only** — no LLM calls, no API keys, no network access. Zero npm dependencies: pure Node stdlib plus the Apify runtime that ships in the official base image (no `npm install`).

### Why

LLM output and exported data are routinely *almost* valid: single-quoted JSON, trailing commas, Markdown fences, unquoted keys, smart quotes, invisible characters, duplicate rows, numbers stored as strings. This Actor cleans that up and tells you exactly what it changed.

### Use cases

- Clean LLM output before `JSON.parse` (fences, single quotes, trailing commas, unquoted keys).
- Normalize exported CSV/log rows: invisible chars, whitespace, NFKC, exact-duplicate rows.
- Validate a payload against a JSON Schema and coerce `"30"` → `30` where the schema says so.

### Input

| Field | Type | Description |
|---|---|---|
| `content` | string (required) | Raw content, **max 1 MB** (larger input returns `INPUT_TOO_LARGE`). |
| `contentType` | `auto` / `json` / `csv` / `text` | Default `auto` (detect from content). |
| `jsonSchema` | string | Optional JSON Schema; enables validation + safe type coercion. |
| `options` | object | `repairJson`, `stripInvisible`, `normalizeWhitespace`, `nfkc`, `dedupeRows`, `coerceTypes` — all default `true`. |
| `maxPreviewItems` | integer | 0–50, default 5. |

### Output (dataset)

One item per run:

| Field | Description |
|---|---|
| `ok` | false only for fatal conditions (`INPUT_TOO_LARGE`, unparseable JSON, invalid schema) |
| `error` | error code when `ok=false` |
| `detectedType` | `json` / `csv` / `text` / `unknown` |
| `cleanedText` | cleaned content, ready to parse or save |
| `data` | structured result (object/array or `{rows}` / `{lines}`) |
| `issues[]` | what was fixed and why (`JSON_SINGLE_QUOTES`, `JSON_TRAILING_COMMA`, `JSON_MARKDOWN_FENCE`, `JSON_UNQUOTED_KEY`, `INVISIBLE_CHARS`, `SMART_QUOTES`, `WHITESPACE`, `NFKC_NORMALIZED`, `DEDUPED_ROWS`, `TYPE_COERCED`, `SCHEMA_VIOLATION`, `JSON_PARSE_FAILED`, `SCHEMA_INVALID`) |
| `warnings[]` | **explicitly lists heuristic guesses** (e.g. "single quotes were interpreted as JSON string delimiters"). Read these before trusting the output. |
| `stats` | inputBytes / outputBytes / removedInvisible / dedupedRows / repairedJson / coercedFields |
| `preview` | first N structured rows |

### Example

Input:

````
content: "```json\n{'name': 'Alice', 'age': '30', 'tags': ['a','b',], city: 'Guilin',}\n```"
````

Result: `ok=true`, `repairedJson=true`, `cleanedText={"name":"Alice","age":"30","tags":["a","b"],"city":"Guilin"}` with issues `JSON_MARKDOWN_FENCE`, `JSON_SINGLE_QUOTES`, `JSON_TRAILING_COMMA`, `JSON_UNQUOTED_KEY` and one warning per heuristic.

### Honesty notes

- The Actor **does not invent missing data**. Unparseable JSON stays unparseable (`ok=false`, `JSON_PARSE_FAILED`).
- Heuristics (single quotes as JSON delimiters, unquoted keys, fence stripping, smart-quote normalization, dedupe) are deterministic but *assumptions*; every one is listed in `warnings[]`.
- CSV handling targets standard RFC4180; exotic dialects may need review.
- No PDF/OCR support (separate Actors cover that).

### Local run

```
node main.js   # reads apify_storage/key_value_stores/default/INPUT.json or ./INPUT.json
```

### Sample output

```json
{
  "ok": true,
  "error": null,
  "detectedType": "json",
  "cleanedText": "{\"name\":\"Alice\",\"age\":\"30\",\"tags\":[\"a\",\"b\"],\"city\":\"Guilin\"}",
  "data": {
    "name": "Alice",
    "age": "30",
    "tags": [
      "a",
      "b"
    ],
    "city": "Guilin"
  },
  "issues": [
    {
      "code": "JSON_MARKDOWN_FENCE",
      "message": "markdown code fence stripped"
    },
    {
      "code": "JSON_SINGLE_QUOTES",
      "message": "single-quoted strings converted to double quotes"
    },
    {
      "code": "JSON_TRAILING_COMMA",
      "message": "trailing commas removed"
    },
    {
      "code": "JSON_UNQUOTED_KEY",
      "message": "unquoted object keys quoted"
    }
  ],
  "warnings": [
    "A Markdown code fence was stripped before parsing (heuristic).",
    "Single quotes were interpreted as JSON string delimiters (heuristic).",
    "Unquoted keys were assumed to be property names (heuristic).",
    "Content type was auto-detected as json (starts with { or [); set contentType to make it explicit."
  ],
  "stats": {
    "inputBytes": 79,
    "outputBytes": 60,
    "removedInvisible": 0,
    "dedupedRows": 0,
    "repairedJson": true,
    "coercedFields": 0
  },
  "preview": [
    {
      "name": "Alice",
      "age": "30",
      "tags": [
        "a",
        "b"
      ],
      "city": "Guilin"
    }
  ]
}
```

### Privacy & data

- Runs entirely inside the Actor container: **no network calls, no external APIs, no data leaves the run** except the dataset you can export.
- The input is processed in memory; only the single output item is written to the dataset.
- No Apify Proxy / no full permissions needed (limited permissions).

### Permissions

Limited permissions. The Actor only reads its input and writes its dataset item; it does not access the internet or your other storages.

### Pricing

Free (pay-per-usage free tier). Pay-per-event pricing may be enabled later. Up to 1 MB input per run; larger inputs return `INPUT_TOO_LARGE` without processing.

License: MIT

# Actor input Schema

## `content` (type: `string`):

Paste JSON, CSV, or plain text (LLM output, logs, exported rows). Max 1 MB.

## `contentType` (type: `string`):

How to interpret content. auto detects JSON/CSV/text; set explicitly for ambiguous input.

## `jsonSchema` (type: `string`):

JSON Schema as text. When set, output is validated and coercible values are converted.

## `options` (type: `object`):

All enabled by default.

## `maxPreviewItems` (type: `integer`):

How many structured rows to include in the preview field (0-50).

## Actor input object example

```json
{
  "contentType": "auto",
  "maxPreviewItems": 5
}
```

# Actor output Schema

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

Cleaned and structured results, one item per processed input.

# 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("pacific_waterside/structured-data-fixer").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("pacific_waterside/structured-data-fixer").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 pacific_waterside/structured-data-fixer --silent --output-dataset

```

## MCP server setup

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

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/0VBdSNdS6RnBHkw8h/builds/Ceoqb1btzQCNGiJ2u/openapi.json
