JSON Repair

Automatically fix malformed, dirty, or invalid JSON. Repair unquoted keys, single quotes, trailing commas, comments, and python/javascript literal types instantly.

How to Repair Invalid & Malformed JSON Online

1

Input Dirty JSON

Paste malformed JSON with single quotes or unquoted keys on the left, click Upload, or click Sample.

2

Choose Indentation

Select your indentation preference (2 Spaces, 4 Spaces, or Minified compact single-line).

3

Copy Repaired Result

Repairs instantly in real time. Click Copy or Download to export clean RFC 8259 JSON.

Tool Options

Unquoted Keys & Single Quotes

Automatically wraps unquoted object keys ({name: "Alice"}) and converts single quotes ('admin') to standard double quotes.

Trailing Commas & Comments

Strips illegal trailing commas in array/object lists ([1, 2,]) and removes inline JavaScript comments (// comment).

Python & JS Type Normalization

Normalizes Python literals (True, False, None) and JavaScript values (undefined, NaN) to valid JSON types.

Tool Limitation & Structural Syntax Notice

This tool automatically repairs syntax quirks such as unquoted keys, single quotes, trailing commas, comments, and non-standard literals. However, for severely broken structural syntax (such as truncated strings or unclosed braces { "a":), repair is not possible without structural data. In those cases, use our JSON Syntax Validator to locate exact token errors.

Your Data Privacy

Web Tool
Privacy-First Architecture
Most of our web tools process your data entirely in-browser. Where server processing is technically required, payloads are evaluated statelessly in-memory and are never stored, saved, or logged.
REST API
Stateless In-Memory Processing
When you use our API endpoints, your requests are processed strictly in-memory without persistent database storage, disk logging, or data retention.
Want to learn more about how we safeguard your information and infrastructure?
Read our full Privacy Policy for detailed security standards, data retention principles, and compliance guarantees.

What does the JSON Repair Tool do?

The JSON Repair Tool automatically cleans and repairs malformed, dirty, or non-standard JSON payloads into valid RFC 8259 compliant JSON in real time. Executing 100% in-browser on blueutils.com, it resolves unquoted object keys ({name: "Alice"}), single-quoted strings ({'role': 'admin'}), trailing commas in lists and objects ([1, 2,]), inline JavaScript comments (// notes), and Python literal representations (True, False, None).

  • Real-Time Zero-Latency Parsing: Sanitizes and repairs JSON as you type, providing live before-and-after byte size metrics (X B → Y B).
  • Configurable Indentation & Minification: Format with 2 Spaces, 4 Spaces, or Minified compact single-line output.
  • Line & Column Error Diagnostics: Detects irreparable structural breaks and pinpoints failing line numbers in red.

Core Concepts & Technical Specifications

  1. Syntax Tree Sanitization:
    • Unquoted Keys ({key: "val"}) → {"key": "val"}: Wraps bare object property identifiers in double quotes.
    • Single Quotes ('val') → "val": Converts single quotes to RFC 8259 compliant double quotes while preserving internal escaped quotes.
    • Trailing Commas ([1, 2,]) → [1, 2]: Strips dangling commas before closing braces and brackets.
    • Inline Comments (// comment): Strips single-line and multiline comments (/* ... */) that break strict JSON parsers.
    • Python & JS Literals: Normalizes Python True/False/None and JavaScript undefined/NaN/Infinity into standard JSON literals (true, false, null).
  2. Structural Error Boundaries:
    • Repairs syntax quirks without corrupting string content.
    • For severe structural damage (such as unclosed braces or truncated files), repair is safely rejected to prevent invalid data fabrication.
  3. In-Browser Privacy:
    • All repair algorithms and AST transformations execute locally in browser memory.
    • No data is logged, stored, or transmitted over remote networks.

How to use the tool?

  1. Input Dirty JSON:
    • Paste malformed JSON, a JavaScript object literal, or Python dictionary dump into the left editor, click Upload to load a local file, or click Sample to load a pre-configured malformed payload.
  2. Choose Indentation:
    • Select 2 Spaces, 4 Spaces, or Minified from the top toolbar.
  3. Copy or Download:
    • Clean, valid JSON appears instantly in the right editor. Click Copy to copy to your clipboard or Download to save as output.json.

Pipeline & Contextual Workflows

  • LLM Output Sanitization: Clean malformed outputs produced by AI models (often returning unquoted keys, single quotes, or Python literals) before parsing in backend applications.
  • Deep Syntax Diagnostics: If a document is severely truncated or contains structural errors, locate exact line coordinates using JSON Syntax Validator.
  • TypeScript Generation: Generate typed interfaces from repaired JSON payloads using JSON to TypeScript Converter.

REST API Integration

blueutils.com provides a free REST API endpoint (POST https://blueutils.com/api/json/repair) for automated ETL pipelines, CI/CD validation, and LLM output parsing.

API Request Parameters

Name Type Description Example
rawText / json String / Object Malformed JSON string, object literal, or Python dict dump to repair. "{name: 'John', age: 30,}"
indent Number/String Optional. Indentation spaces (2, 4, or 'tab'). Default is 2. 2
minify Boolean Optional. If true, returns compact single-line repaired JSON. Default is false. false

API Request Payload Examples

cURL (Formatted JSON Output)

curl -X POST https://blueutils.com/api/json/repair \
  -H "Content-Type: application/json" \
  -d '{
    "rawText": "{name: '\''John'\'', age: 30, active: True,}",
    "indent": 2
  }'

cURL (Minified Compact Mode)

curl -X POST https://blueutils.com/api/json/repair \
  -H "Content-Type: application/json" \
  -d '{
    "rawText": "{endpoint: '\''/api/v1'\'', count: 10,}",
    "minify": true
  }'

Python

import requests

url = "https://blueutils.com/api/json/repair"
payload = {
    "rawText": "{name: 'John', age: 30, active: True,}",
    "indent": 2
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonPayload = """
            {
                "rawText": "{name: 'John', age: 30, active: True,}",
                "indent": 2
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://blueutils.com/api/json/repair"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

API Response Parameters

Name Type Description Example
isValid Boolean Returns true if the payload was successfully repaired into valid JSON. true
result String Clean, formatted 100% valid RFC 8259 JSON payload. "{\n \"name\": \"John\",\n \"age\": 30\n}"
data Object / Array Parsed native object/array representation returned when repair succeeds. {"name":"John","age":30}
repaired Boolean Indicates whether repair modifications were applied. true
originalSize Number Byte size of raw input payload in UTF-8. 42
resultSize Number Byte size of clean repaired JSON payload in UTF-8. 48
error String Detailed error explanation returned when data cannot be repaired. "Unable to repair JSON payload: Source data has structural syntax errors"

API Response Payload Examples

Success Response (HTTP 200 OK)

{
  "isValid": true,
  "result": "{\n  \"name\": \"John\",\n  \"age\": 30,\n  \"active\": true\n}",
  "data": {
    "name": "John",
    "age": 30,
    "active": true
  },
  "repaired": true,
  "originalSize": 42,
  "resultSize": 48
}

Validation Failure Response (HTTP 400 Bad Request)

{
  "isValid": false,
  "error": "Unable to repair JSON payload: Source data has structural syntax errors (Line 1, Column 12)."
}

Rate Limit Exceeded Response (HTTP 429 Too Many Requests)

{
  "error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}

Why use an API to repair JSON?

Automating JSON repair accelerates processing across data ingestion systems:

  • LLM Pipeline Fault Tolerance: AI agents often produce trailing commas, unquoted keys, or Python literals. API repair enables automated recovery without costly model retries.
  • Third-Party Webhook Ingestion: Sanitizes dirty JSON emitted by legacy endpoints and logging pipelines before writing to strict databases.
  • Deterministic AST Integrity: Repairs syntax without corrupting embedded quotes or altering nested string structures.

Native Usage

Repair malformed JSON locally across terminal environments and programming runtimes:

Browser DevTools Console

// Evaluate loose object literal to clean JSON in browser console
const dirty = "{name: 'John', age: 30, active: true,}";
const clean = JSON.stringify(Function(`return (${dirty})`)(), null, 2);
console.log(clean);

Linux / macOS (Node.js jsonrepair CLI)

# Repair JSON using jsonrepair via npx
npx -y jsonrepair "{name: 'John', age: 30, active: True,}"

Windows (PowerShell)

# Repair JSON using Node.js in PowerShell
node -e "const { jsonrepair } = require('jsonrepair'); console.log(jsonrepair('{name: ''John'', age: 30,}'));"

Python

import ast
import json

dirty_str = "{'name': 'John', 'age': 30, 'active': True,}"
try:
    py_dict = ast.literal_eval(dirty_str)
    clean_json = json.dumps(py_dict, indent=2)
    print(clean_json)
except Exception as e:
    print("Repair error:", e)

Java (Jackson with JsonReadFeature)

import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;

public class Main {
    public static void main(String[] args) throws Exception {
        String dirtyJson = "{name: 'John', age: 30,}";

        ObjectMapper mapper = JsonMapper.builder()
            .enable(JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES)
            .enable(JsonReadFeature.ALLOW_SINGLE_QUOTES)
            .enable(JsonReadFeature.ALLOW_TRAILING_COMMA)
            .build();

        Object parsed = mapper.readValue(dirtyJson, Object.class);
        String cleanJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(parsed);
        System.out.println(cleanJson);
    }
}

Frequently Asked Questions (FAQ)

What common syntax mistakes make JSON invalid?

Common JSON errors include unquoted keys ({name: "Alice"}), single-quoted strings ({'role': 'admin'}), trailing commas ([1, 2,]), inline JavaScript comments (// note), and Python boolean/null literals (True, False, None).

How does the JSON Repair Tool fix dirty or malformed JSON?

The tool executes AST syntax tree parsing to wrap unquoted keys in double quotes, convert single quotes, strip trailing commas and comments, and normalize non-standard primitives into 100% valid RFC 8259 JSON.

Can the repair tool fix truncated or severely broken JSON?

Minor syntax quirks (unquoted keys, missing quotes, trailing commas) are repaired automatically. However, severely truncated strings or missing brackets require manual data restoration using our JSON Syntax Validator.

How does the tool handle Python dict dumps (True, False, None)?

Python literal keywords are automatically mapped to standard JSON equivalents: True becomes true, False becomes false, and None becomes null.

Is my JSON payload saved or uploaded to remote servers when repairing?

No. All repair transformations and validation checks run 100% in-browser client-side. Your sensitive configurations and API payloads never leave your local machine.

Rate Limits

UI Limits
100 uses per 15 minutes
Max payload size: 5 MB
API Limits
5 requests per 60 minutes
Max payload size: 256 KB
Need higher API rate limits, increased payload sizes, or custom developer solutions?
Contact our engineering team at support@blueutils.com for custom rate limit increases, higher quota allocations, or tailored enterprise integrations.