JSON Missing Bracket Error: How to Find and Fix It (2026)
Getting a JSON missing bracket error or 'Unexpected end of JSON input'? Learn exactly why it happens, how to find the missing bracket, and how to auto-repair it online.
Have broken JSON right now? Fix it free in under 1 second — no signup.
Fix My JSON →A JSON missing bracket error happens when a {, }, [, or ] is absent — and the result is a JSON string that never properly closes. The parser reaches the end of the input without finding a matching bracket, throws an error, and stops.
This post covers what the error looks like, why it happens (including from LLM outputs), and every practical way to find and fix it.
What Does a JSON Missing Bracket Error Look Like?
The error message depends on your runtime, but all point to the same problem:
| Runtime | Error Message |
|---|---|
| Node.js / Browser | SyntaxError: Unexpected end of JSON input |
| Python | json.decoder.JSONDecodeError: Expecting ',' delimiter: line X column Y |
| Java (Gson) | EOFException: End of input at line X column Y |
| Go | unexpected end of JSON input |
| Ruby | JSON::ParserError: 743: unexpected token |
The phrase "unexpected end" is the giveaway — the parser reached EOF while still inside an open object or array, waiting for a bracket that never came.
Here's a minimal example:
{
"user": {
"name": "Alice",
"role": "admin"
Missing: the closing } for "user" and the closing } for the outer object. The parser reports Unexpected end of JSON input because it ran out of characters while still inside two open objects.
Why Missing Bracket Errors Happen
LLM Output Truncation (Most Common in 2026)
The most common cause in modern development: a language model generates JSON but gets cut off by a token limit or max_tokens setting. The model starts a valid structure, fills it in, then the output window ends mid-object.
# The LLM was asked to return a list of users
response = openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Return 10 users as JSON"}],
max_tokens=200 # Too low for 10 full user objects
)
# Returns: {"users": [{"name": "Alice", "age": 30}, {"name": "Bob",
# Missing: }, ]} — truncated mid-object
When max_tokens is too low relative to the expected output size, the model just stops generating mid-structure. The JSON is structurally incomplete.
max_tokens, use streaming with buffer validation, or use our JSON repair tool to recover the partial output.
Manual Editing
Deleting a block of JSON without cleaning up its brackets is the second most common cause. You remove a section, forget to remove its closing }, or accidentally delete it.
{
"config": {
"debug": true,
"timeout": 30
},
"database":
// <-- deleted the value for "database" but left the key
Nested Structure Mistakes
Deep nesting makes it easy to lose track of which brackets are open:
{
"order": {
"items": [
{
"product": {
"name": "Widget",
"variants": [
{ "color": "red", "stock": 10 },
{ "color": "blue"
// ^^ missing } to close variant, ] to close variants array,
// } to close product, } to close item, ] to close items, } to close order, } to close root
Six missing brackets from one unclosed inner object.
API Response Truncation
Some APIs have response size limits. If the JSON payload exceeds the limit, the response gets cut off in the middle of the structure. The HTTP response completes (200 OK) but the body is incomplete JSON.
Copy-Paste Errors
Copying JSON from a browser, terminal, or document sometimes clips the last few characters if the selection didn't reach the very end of the text. The beginning looks fine, the end is gone.
How to Find the Missing Bracket
Method 1: Count Brackets Manually (Small Files)
For short JSON, count opening vs closing brackets:
Opening: { { [ { { = 5 opening
Closing: } } ] = 3 closing
Missing: 2 closing }
You need equal numbers of { and }, and equal numbers of [ and ].
Method 2: Use a JSON Validator
Paste into AI JSONMedic or any JSON validator. A good validator not only reports the error but also tells you which line the last valid token was on — the missing bracket is either at that line or right after the deepest open block.
Method 3: Regex Bracket Counting (Code)
function findMissingBrackets(jsonStr) {
let curly = 0;
let square = 0;
for (let i = 0; i < jsonStr.length; i++) {
const ch = jsonStr[i];
if (ch === '{') curly++;
else if (ch === '}') curly--;
else if (ch === '[') square++;
else if (ch === ']') square--;
}
return {
missingClosingCurly: Math.max(0, curly), // { without }
extraClosingCurly: Math.max(0, -curly), // } without {
missingClosingSquare: Math.max(0, square), // [ without ]
extraClosingSquare: Math.max(0, -square), // ] without [
};
}
const broken = '{"user": {"name": "Alice", "tags": ["admin"';
console.log(findMissingBrackets(broken));
// { missingClosingCurly: 2, extraClosingCurly: 0, missingClosingSquare: 1, extraClosingSquare: 0 }
This tells you what's missing — though not exactly where, just how many.
Method 4: VS Code Bracket Pair Colorizer
Open the JSON in VS Code. The built-in bracket pair colorizer (enabled by default since VS Code 1.60) color-codes matching brackets. An unmatched bracket shows in gray or red — that's your missing pair.
How to Fix a Missing Bracket
Fix 1: Auto-Repair Online
The fastest fix is to paste the broken JSON into AI JSONMedic. The repair engine:
- Detects unclosed objects and arrays
- Determines the correct nesting depth at end-of-input
- Appends the minimum number of closing brackets needed
- Validates the repaired result
This works especially well for LLM truncation, where the JSON just needs N closing brackets appended to become valid.
Fix 2: Repair in JavaScript
function repairMissingBrackets(jsonStr) {
// Strip whitespace from end
const trimmed = jsonStr.trimEnd();
const stack = [];
let inString = false;
let escape = false;
for (const ch of trimmed) {
if (escape) { escape = false; continue; }
if (ch === '\\' && inString) { escape = true; continue; }
if (ch === '"') { inString = !inString; continue; }
if (inString) continue;
if (ch === '{') stack.push('}');
else if (ch === '[') stack.push(']');
else if (ch === '}' || ch === ']') stack.pop();
}
// Append closing brackets in reverse order
return trimmed + stack.reverse().join('');
}
// Example: LLM-truncated JSON
const truncated = '{"users": [{"name": "Alice", "age": 30}, {"name": "Bob"';
const repaired = repairMissingBrackets(truncated);
console.log(repaired);
// {"users": [{"name": "Alice", "age": 30}, {"name": "Bob"}]}
console.log(JSON.parse(repaired)); // Works!
This stack-based approach correctly handles any nesting depth. It tracks what closing bracket is needed at each level and appends them all at the end.
Fix 3: Repair in Python
def repair_missing_brackets(json_str: str) -> str:
"""Append missing closing brackets to truncated JSON."""
trimmed = json_str.rstrip()
stack = []
in_string = False
escape = False
for ch in trimmed:
if escape:
escape = False
continue
if ch == '\\' and in_string:
escape = True
continue
if ch == '"':
in_string = not in_string
continue
if in_string:
continue
if ch == '{':
stack.append('}')
elif ch == '[':
stack.append(']')
elif ch in ']}':
if stack and stack[-1] == ch:
stack.pop()
return trimmed + ''.join(reversed(stack))
# Example
broken = '{"items": [{"id": 1, "name": "Widget"}, {"id": 2'
fixed = repair_missing_brackets(broken)
print(fixed)
# {"items": [{"id": 1, "name": "Widget"}, {"id": 2}]}
import json
print(json.loads(fixed)) # {'items': [{'id': 1, 'name': 'Widget'}, {'id': 2}]}
Fix 4: Use the json-repair npm Package
For Node.js projects, the json-repair package handles this automatically:
// npm install json-repair
import { jsonrepair } from 'json-repair';
const broken = '{"data": [{"id": 1}, {"id": 2';
const fixed = jsonrepair(broken);
console.log(fixed);
// {"data": [{"id": 1}, {"id": 2}]}
The package handles trailing commas, missing brackets, unquoted keys, single quotes, and about a dozen other common issues in one call.
Fix 5: Use jsonrepair Python Package
# pip install jsonrepair
from jsonrepair import repair_json
broken = '{"config": {"debug": true, "timeout": 30'
fixed = repair_json(broken)
print(fixed)
# {"config": {"debug": true, "timeout": 30}}
Fixing LLM-Truncated JSON at Scale
If you're running a pipeline where an LLM generates JSON and you occasionally get truncated outputs, add a repair step before parsing:
import json
from jsonrepair import repair_json
def parse_llm_json(raw: str) -> dict:
"""Parse LLM-generated JSON, repairing truncation if needed."""
try:
return json.loads(raw)
except json.JSONDecodeError:
try:
repaired = repair_json(raw)
return json.loads(repaired)
except Exception as e:
raise ValueError(f"Could not repair JSON: {e}\nInput: {raw[:200]}")
# In production, log the repair event for monitoring
def parse_llm_json_with_logging(raw: str, logger=None) -> dict:
try:
return json.loads(raw)
except json.JSONDecodeError as original_error:
try:
repaired = repair_json(raw)
result = json.loads(repaired)
if logger:
logger.warning(f"Repaired truncated JSON: {original_error}")
return result
except Exception as e:
raise ValueError(f"Unrecoverable JSON: {e}")
The two-step approach — try strict parse first, repair on failure — adds minimal overhead when JSON is valid, and saves the pipeline when truncation happens.
Preventing Missing Bracket Errors
Increase max_tokens for LLM Calls
# Before: too low
response = client.chat.completions.create(
model="gpt-4o",
max_tokens=200, # Too low for structured output
...
)
# After: size the token budget for your output
response = client.chat.completions.create(
model="gpt-4o",
max_tokens=2000, # Match to expected output size
...
)
As a rule: estimate the JSON output in tokens (roughly 1 token per 4 characters), and set max_tokens to at least 2x that estimate.
Use Native Structured Output
OpenAI, Anthropic, and Google Gemini all offer structured output modes that guarantee valid JSON:
# OpenAI structured output — JSON Schema enforced server-side
from pydantic import BaseModel
class UserList(BaseModel):
users: list[dict]
response = client.beta.chat.completions.parse(
model="gpt-4o",
messages=[...],
response_format=UserList,
)
result = response.choices[0].message.parsed # Always valid
With structured output, the model is constrained to generate tokens that conform to the schema. Truncation can still happen (if max_tokens is too low) but the schema constraint prevents many other structural errors.
Validate at the API Layer
Add a JSON validation step immediately after receiving any API response:
import Ajv from 'ajv';
const ajv = new Ajv();
const schema = {
type: 'object',
properties: {
users: { type: 'array', items: { type: 'object' } }
},
required: ['users']
};
const validate = ajv.compile(schema);
function processApiResponse(rawJson: string) {
const parsed = JSON.parse(rawJson); // Throws on missing bracket
if (!validate(parsed)) {
throw new Error(`Schema validation failed: ${ajv.errorsText(validate.errors)}`);
}
return parsed;
}
Catching the error at the API layer (before it propagates into your business logic) makes debugging much faster. See our JSON schema validation guide for more on schema-based validation.
FAQ
Q: I'm getting "Unexpected end of JSON input" — does that always mean a missing bracket?Usually, yes. "Unexpected end of JSON input" means the parser hit EOF while still inside an open structure. The missing item is typically a closing } or ], but it can also be a closing " for an unterminated string. Check for both.
Use the bracket counting function from Method 3 above. It tells you how many of each bracket type are missing, not where. To find where, use VS Code's bracket pair colorizer or paste into AI JSONMedic — the repair tool will show you what was appended.
Q: The error says "position 743" — how do I count to that position?In VS Code, the character position is shown in the status bar (bottom right). Open the JSON file, press Ctrl+G (Go to Line), then scroll to that character. Alternatively, use the JSON repair tool — it repairs without needing you to locate the exact position.
If the JSON was truncated by an LLM, the repaired version is valid but missing data. The repair only adds the closing brackets — it can't invent the missing field values. For LLM truncation, increase max_tokens and re-run the request to get the complete output.
Yes. JSON5 and JSONC relax rules around trailing commas, comments, and quotes, but they still require all brackets to be properly closed. Missing brackets are a structural error, not a syntax extension.
Q: My JSON passes JSONLint but I'm still getting a parse error in production. Why?JSONLint may be using a more lenient parser. Try validating with JSON.parse() directly (copy into a browser console: JSON.parse(yourString)). If that throws but JSONLint passes, the tool is being lenient. Production runtimes use strict parsing — always test with the actual parser you use in code.
Related Resources
- Fix Trailing Comma in JSON — the other most common JSON syntax error
- JSON Syntax Errors Explained — full taxonomy of every JSON error type
- LLM JSON Repair Guide — comprehensive guide to fixing AI-generated JSON
- Fix JSON with Python — Python-specific JSON error handling
- JSON Studio — repair, format, validate, and diff JSON in one workspace
Missing bracket errors are structural — the JSON document is incomplete. The fastest fix is to paste into AI JSONMedic and get repaired JSON in one click. For production pipelines, add a repair step before parsing and increase max_tokens on LLM calls to prevent truncation in the first place.
Still dealing with broken JSON?
Paste it in and get it fixed in under 1 second — free, no signup, no install. Works with ChatGPT, Claude, n8n, and any AI output.
Fix My JSON Free →Related Articles