# JSON Repair (`dr.skywalker/json-repair`) Actor

Repair malformed JSON documents and return the repaired JSON, parsed value, and repair details for each attempted document.

- **URL**: https://apify.com/dr.skywalker/json-repair.md
- **Developed by:** [Luqin Wang](https://apify.com/dr.skywalker) (community)
- **Stats:** 2 total users, 1 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

## JSON Repair

Repair malformed JSON and publish one result for each input document attempted. Valid JSON documents return successful results with an empty repair report. Successful JSON text uses compact formatting.

Each result contains `recordId`, `document_index`, `repaired_json`, `document`, `repairs`, `fully_repaired`, and `error`. `repaired_json` is valid JSON on success and may contain partial text on failure; `document` is the parsed JSON value on success and `null` on failure. JSON values may be objects, arrays, strings, numbers, booleans, or `null`.

### Input

Supply exactly one of these fields:

| Field | Description |
|---|---|
| `inputText` | One JSON document as text. |
| `inputTexts` | An ordered array of JSON document strings, with at most 100,000 entries. |
| `inputUrl` | A URL returning one JSON document. HTTP and HTTPS destinations must resolve entirely to public addresses. |
| `inputDatasetId` | An Apify dataset ID or local dataset name. Every row must contain a `sourceText` string; rows are read in storage order. |

The total size of source content is limited to 8 MiB in UTF-8, across the entire list or dataset, with at most 100,000 documents. Input envelopes and dataset pages are parsed incrementally under a separate serialized-byte cap, enforcing decoded source bytes and document count before constructing the full list. Local input files are size-checked and admitted before SDK initialization, including files without storage metadata. URL downloads cap total HTTP response bytes at 8 MiB before parsing headers or decoding chunks, including chunk extensions, trailers, and redirects; decoded content has a separate 8 MiB cap. Reads use chunks up to 64 KiB with the reference's 30-second socket timeout. Every redirect revalidates DNS and connects to the checked address; discarded redirect bodies are closed without reading, and at most five redirects are followed. Ambiguous input (multiple source fields) and missing input are rejected. API callers may also provide a raw string or list of strings directly.

Each document is limited to nesting depth 128, 500,000 lexical/decoded items (including object keys), and 10,000 repairs. A conservative 384 MiB run workspace budget may refuse repair of an admitted document; that document receives a partial result and `workspace_limit` error. No salvage is attempted for incomplete strings or decimal/exponent continuations. Numbers that cannot retain their decimal value through serialization return `number_precision` rather than a changed value. A lone-surrogate source receives `invalid_unicode`; its original is preserved with JSON escapes and the batch continues.

### Output

The default dataset contains one item per attempted document, including already-valid and unrepairable documents. Dataset rows containing lone surrogates and large dataset rows over 5 MiB are stored in the key-value store as `RESULT-<8-digit-index>` records; their dataset row contains `document_index`, `recordId`, `fully_repaired`, `result_key`, and `result_manifest_key` to locate the result. The manifest key is `null` when the result fits in a single storage record. Result envelopes use key-value store fragments capped at 7 MiB each.

`OUTPUT.json` is a summary containing `resultPrefix`, `input_documents`, `charged_documents`, `published_documents`, `fully_repaired_documents`, `unrepaired_documents`, and `unpaid_documents`. Individual results are stored separately. The key-value store also contains billing journals and recovery records.

The engine first parses strict JSON. Its deterministic repair layer removes BOMs, surrounding whitespace and Markdown fences; removes comments outside strings; converts single-quoted strings and Python literals; quotes unquoted object keys; removes trailing commas and trailing content; and tries at most two missing-container completions. It never evaluates code. Repair locations refer to the unwrapped input. Unsupported escapes, missing values, mismatched brackets, non-finite numbers and truncated strings produce `fully_repaired: false`, partial text, and an error with details.

For example, `{name:'Ada',active:True,}` produces `{"name":"Ada","active":true}` with reports for the quoted keys, converted string/literal, and removed trailing comma.

### Reliability and billing

- The price is **$0.0001 per attempted document**. Already-valid and unrepairable documents count as attempts. There is no per-run charge.
- Each document has its own one-event billing request immediately before its repair attempt. Its result checkpoint completes before the next document is charged; publication groups contain at most 500 results.
- The actor saves a source snapshot before charging. Billing journals record accepted work, and each charged result is checkpointed before later charges. Dataset publication tracks durable progress so replay can reconcile writes without charging again or duplicating published results.
- Large snapshots and results stream into bounded fragments. Streamed part envelopes have `parts: null`; use the completed manifest's `partCount` and `partPrefix` to read them in order. Fragment payloads concatenate into the original serialized result or source record.
- Unpaid source documents are preserved under `RECOVERY-UNCHARGED-RAW-SUFFIX` with a `PRESERVATION-REPORT`.
- A document-level syntax or complexity failure produces a result and processing continues. Input admission, billing, or storage failures fail the run.

The actor follows the reference's directory layout, Python Docker base, byte limits, billing journal prefixes and charge-first flow. Deliberate differences are one paid document event without a separate run event; per-document result files with an output summary; streaming large envelopes and publishing each bounded group to stay within the memory budget; and rejecting ambiguous inputs or non-HTTP URLs. These changes fit document repair and its bulk inputs. The optional truncated-string salvage layer is omitted to avoid inventing content.

### Run via API

```bash
curl -H "Authorization: Bearer $APIFY_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{"inputTexts": ["{\"name\":\"Ada\",\"active\":True,}", "{\"count\": 3}"]}' \
     "https://api.apify.com/v2/acts/<username>~json-repair/runs?waitForFinish=60"
```

### Local development

```bash
python3 -m pip install -r requirements-dev.txt
mkdir -p storage/key_value_stores/default
## Put {"inputText": "{\"name\":\"Ada\",\"active\":True,}"} in storage/key_value_stores/default/INPUT.json
APIFY_LOCAL_STORAGE_DIR=./storage python3 -m src.main
```

Run the test suite with:

```bash
python3 -m pytest -q
```

The SDK startup integration tests require Apify SDK 4.0.2 installed locally
under the test interpreter (Python 3.10 or newer). They use temporary filesystem
storage with no metadata and prohibit network connections. These three cases
are explicitly skipped when that SDK version is unavailable.

# Actor input Schema

## `inputText` (type: `string`):

One JSON document to repair. Supply exactly one of inputText, inputTexts, inputUrl, or inputDatasetId.

## `inputTexts` (type: `array`):

JSON documents to repair in order. Supply exactly one of inputText, inputTexts, inputUrl, or inputDatasetId. The total source size may not exceed 8 MiB.

## `inputUrl` (type: `string`):

HTTP or HTTPS URL that returns one JSON document. Supply exactly one of inputText, inputTexts, inputUrl, or inputDatasetId.

## `inputDatasetId` (type: `string`):

Apify dataset ID or local dataset name. Each row must contain a sourceText string; documents are processed in storage order. Supply exactly one of inputText, inputTexts, inputUrl, or inputDatasetId. Total source size is limited to 8 MiB and document count to 100,000.

## Actor input object example

```json
{
  "inputText": "{\"name\":\"Ada\",\"active\":True,}"
}
```

# Actor output Schema

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

Dataset containing one item per attempted document. Oversized rows point to a result record in the key-value store.

## `files` (type: `string`):

Key-value store containing OUTPUT.json, per-document result records, billing journals, and recovery records.

# 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 = {
    "inputText": "{\"name\":\"Ada\",\"active\":True,}"
};

// Run the Actor and wait for it to finish
const run = await client.actor("dr.skywalker/json-repair").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 = { "inputText": "{\"name\":\"Ada\",\"active\":True,}" }

# Run the Actor and wait for it to finish
run = client.actor("dr.skywalker/json-repair").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 '{
  "inputText": "{\\"name\\":\\"Ada\\",\\"active\\":True,}"
}' |
apify call dr.skywalker/json-repair --silent --output-dataset

```

## MCP server setup

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

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/F1s7jacgzfhLvoLsi/builds/kptBucjzZbc4UBcjl/openapi.json
