JSON Repair — Fix Broken JSON (incl. ChatGPT/LLM Output)

Output
Repaired JSON
What we fixed
    Examples:

    Last updated: 2026-09-17

    Paste broken or malformed JSON — including output from ChatGPT, Claude, and other LLMs — and this tool repairs it automatically. It strips markdown fences and prose, fixes trailing commas, single quotes, unquoted keys, Python literals, NaN/Infinity, and closes truncated output. You get the repaired JSON plus a list of every fix applied. Everything runs locally in your browser — no data uploaded.

    What this tool does

    Repairs malformed JSON by applying a series of fixes in sequence: stripping markdown fences and prose, unwrapping escaped strings, removing comments, converting single quotes and Python literals, removing trailing commas, replacing NaN/Infinity with null, and closing truncated brackets. The jsonrepair library handles structural fixes like missing commas and unquoted keys. The tool reports every fix applied in a list so you can verify the result.

    Example

    Input (ChatGPT output with prose and fences):

    Sure! Here's the JSON:
    
    ```json
    {
      "users": [
        {"id": 1, "name": "Alice"},
        {"id": 2, "name": "Bob"}
      ]
    }

    Let me know if you need changes!

    
    Output:
    
    ```json
    {
      "users": [
        { "id": 1, "name": "Alice" },
        { "id": 2, "name": "Bob" }
      ]
    }

    Fixes reported:

    What gets fixed

    FixExample inputExample output
    Markdown fences```json {...} ```{...}
    Leading/trailing proseHere's the JSON: {...}{...}
    Single quotes{'a':1}{"a":1}
    Unquoted keys{name:"test"}{"name":"test"}
    Trailing commas{"a":1,}{"a":1}
    Python booleans{"active":True}{"active":true}
    Python None{"value":None}{"value":null}
    NaN/Infinity{"score":NaN}{"score":null}
    Truncated output{"items":["a","b","c"{"items":["a","b","c"]}
    Escaped string"{\"a\":1}"{"a":1}
    <json> tags<json>{"a":1}</json>{"a":1}

    Repairing ChatGPT output

    ChatGPT and similar chat models rarely return raw JSON. They introduce themselves, wrap the payload in a markdown fence, and add a closing remark. Each of those decorations breaks a strict parser. The example below is a realistic assistant response containing a fenced object with a trailing comma, Python-style capitalization on a boolean, and prose on both ends.

    Input:

    Certainly, here is the configuration you asked for:
    
    ```json
    {
      "service": "billing",
      "timeout_ms": 30000,
      "retries": 3,
      "secure": True,
      "endpoints": [
        "https://api.example.com/charge",
        "https://api.example.com/refund",
      ]
    }

    Let me know if you want me to adjust the timeout or retries.

    
    Output:
    
    ```json
    {
      "service": "billing",
      "timeout_ms": 30000,
      "retries": 3,
      "secure": true,
      "endpoints": [
        "https://api.example.com/charge",
        "https://api.example.com/refund"
      ]
    }

    Fixes reported:

    The two prose lines and the fence would each cause a parser to fail before it ever reached the object. Stripping them first lets the rest of the pipeline operate on the payload itself.

    Repairing truncated API responses

    When a streaming or token-limited response cuts off mid-value, the JSON ends without the closing brackets a parser needs. The tool detects the unclosed structures and appends the missing delimiters so the result parses. It also reports how many brackets were added, which tells you the output is reconstructed rather than verbatim.

    Input (response cut off mid-array):

    {
      "query": "laptop stands",
      "total": 214,
      "results": [
        {"id": "A1", "title": "Adjustable Aluminum Stand", "price": 39.99},
        {"id": "A2", "title": "Foldable Bamboo Stand", "price": 24.50},
        {"id": "A3", "title": "Portable Tablet Stan

    Output:

    {
      "query": "laptop stands",
      "total": 214,
      "results": [
        { "id": "A1", "title": "Adjustable Aluminum Stand", "price": 39.99 },
        { "id": "A2", "title": "Foldable Bamboo Stand", "price": 24.5 },
        { "id": "A3", "title": "Portable Tablet Stan" }
      ]
    }

    Fixes reported:

    The last title was truncated mid-word, so the tool closes the string with what it has. The data is incomplete by nature of truncation, but the structure is now valid and you can inspect every returned field. If you control the request, increase the token budget or request a smaller page to avoid the cut-off at the source.

    Repairing Python-style JSON

    Python developers often paste output from print() or a REPL session straight into a JSON tool. Python dict literals look like JSON but use single quotes, capitalize booleans, and write None instead of null. They also tolerate trailing commas, which JSON does not. The tool normalizes all of these.

    Input:

    {'project': 'orion', 'version': '1.4.2', 'enabled': True, 'archived': False, 'owner': None, 'tags': ['internal', 'staging',], 'config': {'port': 8080, 'host': '0.0.0.0'}}

    Output:

    {
      "project": "orion",
      "version": "1.4.2",
      "enabled": true,
      "archived": false,
      "owner": null,
      "tags": [
        "internal",
        "staging"
      ],
      "config": {
        "port": 8080,
        "host": "0.0.0.0"
      }
    }

    Fixes reported:

    Single-quote conversion is a text-level pass, not a full Python parser, so it assumes the input is dict-like. If your Python source uses f-strings that embed quotes in values, verify the output by eye before trusting it.

    The repair pipeline explained

    The tool runs the input through an ordered pipeline. Each step hands its result to the next. Reading them in order explains why a particular fix appears (or does not) in the report.

    1. stripMarkdownFences removes triple-backtick fences and any json language tag so the parser is not tripped up by ``` markers.
    2. stripXmlTags removes wrapper tags such as <json> and </json> that some agents insert around the payload.
    3. unwrapEscapedJson detects when the whole value is a JSON string containing escaped JSON (for example a stringified webhook body) and unwraps it into the inner object.
    4. stripLeadingProse drops conversational text before the first JSON token, such as “Sure, here is the data:”.
    5. stripTrailingProse drops conversational text after the last JSON token, such as “Let me know if you need changes!”.
    6. extractJsonBlocks finds each JSON block in what remains and selects the first one. The count is reported so you can choose a different block if the first was not the one you wanted.
    7. Replace NaN and Infinity with null converts values that are not legal in JSON into null. The report notes how many were replaced.
    8. Fix trailing commas, single quotes, and Python literals removes trailing commas, swaps single quotes for double quotes, and rewrites True, False, and None into true, false, and null.
    9. jsonrepair runs next and handles structural problems the text passes cannot: missing commas between properties, unquoted keys, unterminated strings that need more than a simple close, and mismatched brackets that require insertion rather than just appending.
    10. detectStructuralFixes compares the repaired structure against the original to determine which closings and insertions were structural, so the report can describe them in plain language (for example “Closed 2 unclosed arrays”).
    11. Pretty-print runs JSON.stringify with two-space indentation on the final value so the output is readable and deterministic.

    The order matters. Stripping prose and fences first means the later passes never see the conversational wrapper. Replacing NaN before jsonrepair prevents the library from trying to interpret invalid numeric literals. Running jsonrepair after the text passes means it only has to handle residual structural damage, which is exactly what it is built for.

    Common mistakes when repairing

    When repair cannot help

    Some inputs are damaged past the point of structural reconstruction. The tool will either report that it could not parse the input or produce a best-effort result that is syntactically valid but semantically wrong. Watch for these cases:

    In all of these cases the right move is to fix the source: re-prompt the model, re-issue the API call with a higher token budget, or parse the original format with the correct tool.

    Do it in code

    Node.js (jsonrepair):

    const { jsonrepair } = require('jsonrepair');
    try {
      const repaired = jsonrepair(brokenJson);
      const parsed = JSON.parse(repaired);
      console.log(parsed);
    } catch (e) {
      console.log('Could not repair:', e.message);
    }

    Python:

    import json, re
    
    def repair_json(s):
        # Strip markdown fences
        s = re.sub(r'^```(?:json)?\s*', '', s, flags=re.MULTILINE)
        s = re.sub(r'\s*```$', '', s, flags=re.MULTILINE)
        # Strip prose before/after
        s = s[s.find('{'):s.rfind('}')+1] if '{' in s else s[s.find('['):s.rfind(']')+1]
        # Fix single quotes, Python bools, trailing commas
        s = s.replace("'", '"').replace('True', 'true').replace('False', 'false').replace('None', 'null')
        s = re.sub(r',(\s*[}\]])', r'\1', s)
        return json.loads(s)

    CLI (jsonrepair):

    npx jsonrepair broken.json > fixed.json

    The code snippets above cover the common cases but do not replicate the full browser pipeline. The hosted tool adds prose stripping, escaped-string unwrapping, NaN replacement, truncation closing, and a human-readable fixes report on top of the library.

    Edge cases handled

    Frequently asked questions

    Why do LLMs return broken JSON?
    Large language models generate text token by token. Common failure modes include wrapping JSON in markdown code fences, adding conversational prose before or after the JSON, truncating output when they hit token limits, using single quotes or unquoted keys in a Python style, and adding trailing commas. This tool detects and fixes all of these automatically.
    What types of JSON errors can this repair?
    Trailing commas, single quotes, unquoted keys, comments, Python True False and None, NaN and Infinity, truncated output (auto-closes open brackets and strings), missing commas between properties, markdown code fences, leading and trailing prose, json tags, and escaped-string JSON (a JSON string value that contains JSON unwrapped to a plain object).
    How does truncated output repair work?
    When JSON is cut off mid-value (common when an LLM hits its token limit) the tool detects unclosed brackets, strings, and objects, then closes them automatically. The What we fixed list tells you exactly how many brackets were closed.
    Can I validate the repaired JSON against a schema?
    Yes. Expand the Validate against JSON Schema panel, paste your JSON Schema, and the tool checks the repaired output against it. Schema validation runs entirely in your browser using the cfworker json-schema library.
    Does this tool send my data to a server?
    No. All parsing, repair, and validation happens in your browser. Your data never leaves your device. There is no backend, no API calls, and no analytics that process your input.
    How do I prevent LLMs from returning broken JSON?
    Use structured outputs or function calling when available (OpenAI and Anthropic support this). Provide a JSON Schema in the prompt. Request JSON mode if the API supports it. Add a retry loop that validates the output and re-prompts on failure. This tool is your safety net when those measures fail.
    What if there are multiple JSON blocks in the input?
    The tool detects multiple JSON blocks (for example JSON inside a markdown list) and uses the first one. The What we fixed list notes how many blocks were found, and you can manually select a different block if needed.
    What is the difference between this tool and just running jsonrepair in code?
    The library handles structural fixes such as missing commas and unquoted keys. This tool wraps it with a pipeline that also strips markdown fences and prose, unwraps escaped strings, converts Python literals and single quotes, removes trailing commas, replaces NaN and Infinity with null, closes truncated output, and then pretty-prints the result. It also reports every fix applied in a readable list.
    Does the tool preserve the original key order and number formatting?
    Keys keep their insertion order because the output is produced by JSON.stringify on the parsed value. Numbers are normalized to JavaScript Number formatting, so large integers may lose precision if they exceed the safe integer range. Use the schema validator to catch numeric precision problems before trusting the output for financial or identifiers use.
    Can I repair a JSON file exported from a database dump?
    Yes, as long as the content is JSON or close to JSON. Common dump quirks it handles include single-quoted strings, Python booleans and None, trailing commas, and NaN or Infinity values. If the dump is actually CSV, YAML, or a custom binary format, repair will not work because the input is not JSON-like.

    Related tools