# LLM JSON Repair and Schema Enforcer API (`n4d.h1dr/llm-json-healer`) Actor

Deterministic engine that repairs truncated JSON, unescaped quotes, trailing commas, and markdown wrappers from LLM outputs.

- **URL**: https://apify.com/n4d.h1dr/llm-json-healer.md
- **Developed by:** [Nadim Hider](https://apify.com/n4d.h1dr) (community)
- **Security:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.50 / 1,000 json 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

## LLM JSON Repair and Schema Enforcer API

A deterministic, zero-latency engine that repairs malformed, truncated, or unescaped JSON produced by Large Language Models (LLMs) and autonomous agents. Strips markdown fences, fixes trailing commas, inserts missing closing brackets, autocasts numeric strings, and optionally validates outputs against strict JSON Schema definitions.

***

### Why Use This Actor?

Autonomous agents frequently crash in production because LLMs output malformed JSON:

- Unescaped inner quotes inside string values.
- Trailing commas before closing braces.
- Truncated closing brackets caused by context limits.
- Markdown code block fences wrapping the payload.

This Actor eliminates LLM JSON errors deterministically without making expensive recursive calls back to OpenAI or Anthropic.

***

### Dual Output Envelope (Agent Native)

Every output record contains both structured data and a pre-rendered markdown summary ready for immediate LLM context consumption:

````json
{
  "id": "item-101",
  "success": true,
  "meta": {
    "processing_time_ms": 2.4,
    "items_count": 1
  },
  "data": {
    "repaired_json": {
      "name": "Autonomous Agent",
      "status": "active",
      "tokens": 450,
      "tools": ["search", "calculator"]
    },
    "schema_valid": true,
    "schema_errors": [],
    "fixes_applied": ["Stripped markdown code fences", "Fixed JSON syntax anomalies", "Autocast numeric strings"]
  },
  "markdown_summary": "### JSON Repair Summary\n- Status: Success (Repaired in 2.4ms)\n- Schema Valid: True\n- Fixes Applied: Stripped markdown code fences, Autocast numeric strings\n\n```json\n{\n  \"name\": \"Autonomous Agent\",\n  \"status\": \"active\",\n  \"tokens\": 450,\n  \"tools\": [\"search\", \"calculator\"]\n}\n```"
}
````

***

### Input Schema

| Field | Type | Default | Description |
|---|---|---|---|
| `items` | Array of Objects | *Sample Broken JSON* | Array of objects with `id` and `raw_text` strings to repair. |
| `enforce_schema` | Object | `{}` | Optional JSON Schema to validate and enforce on the output. |
| `autocast_numbers` | Boolean | `true` | Automatically converts numeric strings like '45' to integers. |

***

### Pay-Per-Event (PPE) Pricing

- Primary Event: `json-repaired`
- Cost: **$0.0005 per repaired item** ($0.50 per 1,000 repairs).
- Initial 5 seconds of compute are waived via `apify-actor-start`.

***

### Integration Code in 10+ Languages

#### cURL

```bash
curl -X POST "https://api.apify.com/v2/acts/n4d.h1dr~llm-json-healer/runs?token=YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"items": [{"id": "1", "raw_text": "{\"key\": \"value\",}"}]}'
```

#### Python

````python
from apify_client import ApifyClient

client = ApifyClient("YOUR_API_TOKEN")
run = client.actor("n4d.h1dr/llm-json-healer").call(run_input={
    "items": [{"id": "1", "raw_text": "```json\n{\"score\": \"95\",}\n```"}]
})
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item["data"]["repaired_json"])
````

#### Node.js / TypeScript

```typescript
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: 'YOUR_API_TOKEN' });
const run = await client.actor('n4d.h1dr/llm-json-healer').call({
  items: [{ id: '1', raw_text: '{ name: "Agent", }' }]
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(items[0].data.repaired_json);
```

#### Go

```go
package main
import (
    "bytes"
    "net/http"
)
func main() {
    url := "https://api.apify.com/v2/acts/n4d.h1dr~llm-json-healer/runs?token=YOUR_API_TOKEN"
    payload := []byte(`{"items": [{"id": "1", "raw_text": "{\"test\": 1,}"}]}`)
    http.Post(url, "application/json", bytes.NewBuffer(payload))
}
```

#### Ruby

```ruby
require 'net/http'
require 'json'
uri = URI('https://api.apify.com/v2/acts/n4d.h1dr~llm-json-healer/runs?token=YOUR_API_TOKEN')
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req.body = { items: [{ id: '1', raw_text: '{"status": "ok",}' }] }.to_json
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
```

#### PHP

```php
<?php
$ch = curl_init('https://api.apify.com/v2/acts/n4d.h1dr~llm-json-healer/runs?token=YOUR_API_TOKEN');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'items' => [['id' => '1', 'raw_text' => '{"a": 1,}']]
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
```

#### Java

```java
import java.net.URI;
import java.net.http.*;
public class Main {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.apify.com/v2/acts/n4d.h1dr~llm-json-healer/runs?token=YOUR_API_TOKEN"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString("{\"items\": [{\"id\": \"1\", \"raw_text\": \"{\\\"x\\\": 10,}\"}]}"))
            .build();
        client.send(request, HttpResponse.BodyHandlers.ofString());
    }
}
```

#### C# (.NET)

```csharp
using System.Net.Http.Json;
var client = new HttpClient();
var payload = new { items = new[] { new { id = "1", raw_text = "{\"ready\": true,}" } } };
await client.PostAsJsonAsync("https://api.apify.com/v2/acts/n4d.h1dr~llm-json-healer/runs?token=YOUR_API_TOKEN", payload);
```

#### Rust

```rust
use reqwest::Client;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    let res = client.post("https://api.apify.com/v2/acts/n4d.h1dr~llm-json-healer/runs?token=YOUR_API_TOKEN")
        .json(&serde_json::json!({"items": [{"id": "1", "raw_text": "{\"key\": 1,}"}]}))
        .send().await?;
    Ok(())
}
```

#### Swift

```swift
import Foundation
var request = URLRequest(url: URL(string: "https://api.apify.com/v2/acts/n4d.h1dr~llm-json-healer/runs?token=YOUR_API_TOKEN")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: ["items": [["id": "1", "raw_text": "{\"ok\": true,}"]]])
URLSession.shared.dataTask(with: request).resume()
```

#### n8n / Make.com Webhook Node

Add an HTTP Request node in n8n or Make:

- Method: `POST`
- URL: `https://api.apify.com/v2/acts/n4d.h1dr~llm-json-healer/runs?token=YOUR_API_TOKEN`
- Body Parameters: `{ "items": [ { "id": "={{ $json.id }}", "raw_text": "={{ $json.raw_llm_output }}" } ] }`

# Actor input Schema

## `items` (type: `array`):

List of objects containing raw_text strings from LLM outputs that need deterministic JSON syntax repair.

## `enforce_schema` (type: `object`):

Optional JSON Schema definition to validate and enforce on the repaired JSON output.

## `autocast_numbers` (type: `boolean`):

When true, automatically casts numeric string values like '123' or '45.67' into actual integers and floats.

## Actor input object example

````json
{
  "items": [
    {
      "id": "sample-1",
      "raw_text": "```json\n{\n  \"name\": \"Autonomous Agent\",\n  \"status\": \"active\",\n  \"tokens\": \"450\",\n  \"tools\": [\"search\", \"calculator\",],\n} // truncated\n```"
    }
  ],
  "enforce_schema": {},
  "autocast_numbers": true
}
````

# Actor output Schema

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

No description

# 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 = {
    "items": [
        {
            "id": "sample-1",
            "raw_text": "```json\n{\n  \"name\": \"Autonomous Agent\",\n  \"status\": \"active\",\n  \"tokens\": \"450\",\n  \"tools\": [\"search\", \"calculator\",],\n} // truncated\n```"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("n4d.h1dr/llm-json-healer").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 = { "items": [{
            "id": "sample-1",
            "raw_text": """```json
{
  \"name\": \"Autonomous Agent\",
  \"status\": \"active\",
  \"tokens\": \"450\",
  \"tools\": [\"search\", \"calculator\",],
} // truncated
```""",
        }] }

# Run the Actor and wait for it to finish
run = client.actor("n4d.h1dr/llm-json-healer").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 '{
  "items": [
    {
      "id": "sample-1",
      "raw_text": "```json\\n{\\n  \\"name\\": \\"Autonomous Agent\\",\\n  \\"status\\": \\"active\\",\\n  \\"tokens\\": \\"450\\",\\n  \\"tools\\": [\\"search\\", \\"calculator\\",],\\n} // truncated\\n```"
    }
  ]
}' |
apify call n4d.h1dr/llm-json-healer --silent --output-dataset

````

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,n4d.h1dr/llm-json-healer"
        }
    }
}
```

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/RlYiqWqSHvhmR8fbL/builds/XD4noGhD7KJG0xvSp/openapi.json
