# JSON Repair – Fix Broken JSON from LLM Output (`plainwren/fix-broken-json`) Actor

Turns "almost JSON" from LLMs and logs into valid JSON. Removes code fences and chat text, fixes commas, quotes, comments and Python True/None, and closes cut-off output. Every row lists the fixes applied. Batch up to 10,000 strings per run. You're only charged for items that come back valid.

- **URL**: https://apify.com/plainwren/fix-broken-json.md
- **Developed by:** [Plainwren Studio](https://apify.com/plainwren) (community)
- **Categories:** Developer tools, AI, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.00 / 1,000 item repaireds

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

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

### What is JSON Repair?

**JSON Repair** turns broken or "almost JSON" from LLMs, chatbots and older scripts into **valid JSON**, and tells you **exactly what it fixed**. Paste one string or send **up to 10,000 strings in one run**. Each item becomes one dataset row, in the same order as your input.

It's plain, deterministic code: **no AI calls, no third-party API, no login, no scraping**. Nothing is stored beyond your run's own dataset.

Try it: open the Input tab, keep the two prefilled examples, and click **Start**.

Free single-string check in the browser: [JSON formatter](https://tools.plainwrenstudio.com/json-formatter/). Support: <support@plainwrenstudio.com>.

### What can JSON Repair fix?

Every fix it makes is reported with a fix code, so you can see what changed.

| Problem in your text | Fix code in the output |
|---|---|
| Markdown ` ```json ` code fences (also unclosed) | `removed_code_fence` |
| Chat text before or after the JSON ("Sure! Here is the data:"); inside a code fence this shows as `removed_code_fence` | `removed_leading_text` / `removed_trailing_text` |
| Trailing commas; double or leading commas | `removed_trailing_comma` / `removed_extra_comma` |
| Missing commas | `inserted_missing_comma` |
| Single, smart (“ ”) or backtick quotes | `normalized_quotes` |
| Unquoted keys or bare-word values | `quoted_unquoted_keys` / `quoted_unquoted_values` |
| `//`, `/* */` and `#` comments | `removed_comments` |
| Missing colon, or `=` instead of `:` | `inserted_missing_colon` / `replaced_equals_with_colon` |
| Missing value (`"a": ,`) | `filled_missing_value` (becomes `null`) |
| Python `True` / `False` / `None` | `converted_python_literals` |
| `undefined`, `NaN`, `Infinity` | `replaced_non_json_values` (become `null`) |
| Numbers like `+1`, `.5`, `2.`, `007` | `fixed_number_format` |
| Unescaped quotes inside strings (most cases) | `escaped_inner_quotes` |
| Raw newlines or tabs inside strings | `escaped_control_characters` |
| Bad backslash escapes (an unknown escape like `\d` keeps its backslash, so Windows paths stay intact; `\'` becomes `'`) | `fixed_invalid_escape` |
| `...` placeholders in place of array items or object members (`[1, 2, ...]`). Used as a value (`"a": ...`), it becomes the string `"..."` (`quoted_unquoted_values`) | `removed_ellipsis` |
| `]` where `}` belongs (and the reverse) | `fixed_mismatched_bracket` |
| Output cut off mid-string, object, array, number or `true`/`false`/`null` | `closed_truncated_*` / `completed_truncated_*` / `removed_incomplete_member` |
| JSON wrapped in a JSON string (`"{\"a\":1}"`) | `unwrapped_stringified_json` |
| Byte-order mark at the start | `removed_bom` |

### Who is it for?

- 🧑‍💻 **Developers and AI-agent builders** whose LLM calls return almost-valid JSON: models without a structured-output mode, older or local models, or streams that get cut off.
- 🔗 **No-code and automation users** (Make, Zapier, n8n through Apify's integrations) whose LLM step breaks the next JSON step.
- 🤖 **MCP and agent users**: a low-cost tool an agent can call to fix its own output.
- 🧹 **Data cleanup**: logs or exports full of JavaScript-style objects or Python-style dicts.

### Use cases

- Fix broken JSON or invalid JSON from an LLM that wrapped the object in a code fence, added chat text, or used Python `True` / `None`.
- Repair malformed JSON with trailing commas, missing quotes or cut-off output before the next step in Make, Zapier, n8n or an agent pipeline.
- Clean logs or exports of JavaScript-style objects into valid JSON, with a `fixes` list on each row so you can see what changed.

### How to repair JSON with this Actor

1. Open the **Input** tab.
2. Add your strings to **Texts to repair** (one malformed JSON or LLM reply per item), or use **Single text** for one item.
3. Optional: turn on **Pretty-print output** to indent the result. **Unwrap stringified JSON** is on by default.
4. Click **Start**.
5. Get results from the **Output** tab, or download them as JSON, CSV or Excel. You can also call the Actor through the Apify API, schedule it, or connect it to other tools with Apify integrations.

#### Input example

````json
{
  "texts": [
    "```json\n{name: 'Ada', skills: ['math',], active: True}\n```",
    "Sure! Here is the data: {\"id\": 7, \"tags\": [\"a\" \"b\"], \"note\": \"truncat",
    "no json here"
  ],
  "pretty": false
}
````

| Field | Type | What it does |
|---|---|---|
| `texts` | array of strings | One malformed JSON or LLM output per item. Each becomes one row. |
| `text` | string | One item. Added after `texts` if you send both. |
| `pretty` | boolean (default `false`) | Indent the `repaired` string with 2 spaces. |
| `unwrapStringified` | boolean (default `true`) | If the input is a JSON string that contains a JSON object or array, return the inner value. |

#### Output example

One dataset row per input item, in input order:

```json
{"index":0,"ok":true,"data":{"name":"Ada","skills":["math"],"active":true},"repaired":"{\"name\":\"Ada\",\"skills\":[\"math\"],\"active\":true}","fixes":["removed_code_fence","quoted_unquoted_keys","normalized_quotes","removed_trailing_comma","converted_python_literals"],"error":null,"inputLength":58}
{"index":1,"ok":true,"data":{"id":7,"tags":["a","b"],"note":"truncat"},"fixes":["inserted_missing_comma","closed_truncated_string","closed_truncated_object","removed_leading_text"],"error":null,"inputLength":69}
{"index":2,"ok":false,"data":null,"repaired":null,"fixes":[],"error":"No JSON object or array found in input","inputLength":12}
```

(Row 1 is shortened here.)

| Output field | Meaning |
|---|---|
| `index` | Position of the item, counting from 0 across `texts`, then `text`. |
| `ok` | `true` if valid JSON came back. |
| `data` | The parsed JSON value. |
| `repaired` | The valid JSON as a string. |
| `fixes` | Fix codes for every change made. Empty if nothing was needed. |
| `error` | Plain-language reason when `ok` is `false`. |
| `inputLength` | Length of the input in characters. Present on every row; `null` if the item wasn't text. |

A run summary is saved in the key-value store under `OUTPUT`:

```json
{"total":3,"processed":3,"ok":2,"failed":1,"skipped":0,"stoppedAtLimit":false,"limitReason":null}
```

`skipped` = items not processed and not charged. `limitReason` is `maxItems` or `spendingLimit` when the run stopped early, otherwise `null`.

### How much does it cost to repair JSON?

JSON Repair uses **pay-per-event** pricing, so you pay only for results:

- **$0.001 per repaired item** (`item-repaired`): **$1.00 per 1,000 repaired items**. Charged once for each item that comes back with `ok: true`, including input that was already valid JSON.
- **Items that can't be repaired are free.** They still appear in your dataset with `ok: false` and an error message.
- A small **Actor start** fee of **$0.00005 per run** (Apify's standard start event).

Example: a run with 1,000 strings where 950 are repaired costs 950 × $0.001 + $0.00005 = **about $0.95**.

Apify's free plan includes monthly platform credit you can use to try it.

### Limits

- **It's heuristic.** Ambiguous input can become valid JSON that isn't what the model meant. Check the `fixes` list to see exactly what changed.
- **Cut-off output is closed, not recovered.** A cut-off string stays cut off, and an incomplete last key is dropped (`removed_incomplete_member`).
- **Some inner quotes can't be fixed.** A quote inside a string that's directly followed by a comma, colon, bracket or line break can be read as the end of the string, so the fix fails (`"He said "hi", then left"` comes out wrong).
- **One JSON value per string.** If one string holds several JSON documents (for example JSONL), you get one of them (the longest), not all.
- **No JSON Schema validation** yet. It makes JSON valid; it doesn't check it against your schema.
- **Size limits:** up to 10,000 items per run, 5 million characters per item, nesting depth 512.
- **Items beyond 10,000 are skipped and not charged; the run still succeeds.** The run summary shows how many were skipped. Send them in another run.
- **A result row must be under ~9 MB** (Apify's dataset item limit), so items over ~4 MB come back as a free `ok: false` row with a "too large" error.

### FAQ

#### Does it use AI to fix the JSON?

No. It's deterministic code that runs the same way every time, with no AI model or external API call. The same input always gives the same output.

#### What happens when an item can't be repaired?

You get a row with `ok: false`, `data: null` and a plain error such as "No JSON object or array found in input". You aren't charged for that item.

#### Am I charged for input that is already valid?

Yes. Valid input still comes back with `ok: true` and counts as one repaired item.

#### What happens if I hit my spending limit?

Each row is saved first and charged after. The run stops cleanly before any row it can't pay for, keeps everything already saved, and skips the rest without charging. The run still succeeds, and the summary (`OUTPUT`) shows how many items were skipped, with `limitReason: "spendingLimit"`.

#### Can it bring back data the model never finished writing?

No. It closes open strings, arrays and objects so the JSON parses, but it can't invent missing content.

#### How is this different from open-source libraries like `jsonrepair` (JS) or `json_repair` (Python)?

Those are good if you can install and run code. This Actor is our own code (not a wrapper around those libraries) and is hosted. You don't install anything, you can send batches, you get a per-item fix report, and you can call it from the Apify API, integrations or MCP clients.

#### Can I use it from Make, Zapier, n8n or an AI agent?

Yes, through Apify's integrations and API, the same way as any other Apify Actor.

#### Is my data stored?

Only in your run's own dataset and key-value store, under your Apify account's normal storage retention. It doesn't send your text anywhere else.

#### Something got fixed wrong. What should I do?

Open an issue on the Actor's **Issues** tab with the input (remove anything private) and the output you expected, or email <support@plainwrenstudio.com>.

# Actor input Schema

## `texts` (type: `array`):

One malformed JSON / LLM output string per item. Each item is repaired independently and becomes one dataset row. Up to 10,000 items per run; any extra items are skipped (not charged) and counted in the OUTPUT summary.

## `text` (type: `string`):

Convenience field for one item. Appended after 'texts' if both are given.

## `pretty` (type: `boolean`):

Indent the 'repaired' JSON string with 2 spaces.

## `unwrapStringified` (type: `boolean`):

If the input is a JSON string that itself contains a JSON object/array (e.g. "{"a":1}"), return the inner object.

## Actor input object example

````json
{
  "texts": [
    "```json\n{name: 'Ada', skills: ['math', 'code',], active: True}\n```",
    "Sure! Here is the data: {\"id\": 7, \"tags\": [\"a\" \"b\"], \"note\": \"truncated"
  ],
  "pretty": false,
  "unwrapStringified": true
}
````

# Actor output Schema

## `dataset` (type: `string`):

Dataset of repaired (or failed) JSON items.

## `OUTPUT` (type: `string`):

Totals: processed, ok, failed, skipped, spending-limit stop.

# 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 = {
    "texts": [
        "```json\n{name: 'Ada', skills: ['math', 'code',], active: True}\n```",
        "Sure! Here is the data: {\"id\": 7, \"tags\": [\"a\" \"b\"], \"note\": \"truncated"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("plainwren/fix-broken-json").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

````

## Python example

````python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "texts": [
        """```json
{name: 'Ada', skills: ['math', 'code',], active: True}
```""",
        "Sure! Here is the data: {\"id\": 7, \"tags\": [\"a\" \"b\"], \"note\": \"truncated",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("plainwren/fix-broken-json").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

````

## CLI example

````bash
echo '{
  "texts": [
    "```json\\n{name: '\''Ada'\'', skills: ['\''math'\'', '\''code'\'',], active: True}\\n```",
    "Sure! Here is the data: {\\"id\\": 7, \\"tags\\": [\\"a\\" \\"b\\"], \\"note\\": \\"truncated"
  ]
}' |
apify call plainwren/fix-broken-json --silent --output-dataset

````

## MCP server setup

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

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/4JEkp3NEmdNetbdTL/builds/CGbf7f8oNYBG3LfI2/openapi.json
