Inferensys

Prompt

JSON Structure Repair Prompt Template

A practical prompt playbook for using the JSON Structure Repair Prompt Template in production AI workflows to fix unclosed brackets, trailing commas, and unquoted keys.
Accountant using AI for financial close automation, accounting software on screen, home office evening work session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the precise failure mode this prompt repairs and the integration context where it belongs.

Use this prompt when a model returns a string that looks like JSON but fails to parse. This is a post-generation repair step, not a replacement for structured output prompting. It targets syntax-level defects: unclosed brackets, trailing commas, single-quoted strings, unquoted keys, and comment artifacts. It does not fix semantic schema violations such as missing required fields or incorrect types. Integration engineers and platform developers wire this into a retry loop after a JSON.parse failure, before the payload reaches a downstream API, database, or event bus.

The ideal user is an engineer who already has a target schema and a validator in place. The model output failed structural parsing, but the content is approximately correct. This prompt is the first repair attempt in a retry chain. If it succeeds, the repaired JSON proceeds to schema validation. If it fails, the system escalates to more expensive repair strategies—such as field-level correction prompts or human review. Do not use this prompt when the output is semantically wrong, when the model refuses to answer, or when the failure is a token limit truncation rather than a syntax error. Those failures require different repair playbooks.

Before invoking this prompt, log the raw model output and the parse error message. These artifacts are essential for debugging and for evaluating whether the repair prompt is improving over time. Wire the prompt into a controlled retry loop with a maximum of two repair attempts. If both attempts fail, route the payload to a dead-letter queue for offline analysis. Never silently discard malformed JSON—every repair attempt should produce an audit record that includes the original output, the repair prompt version, the repaired output, and the final parse result. This discipline prevents silent data corruption and makes repair quality measurable across model versions.

PRACTICAL GUARDRAILS

Use Case Fit

Where JSON structure repair works, where it fails, and what you need before you start.

01

Good Fit: Structural Corruption

Use when: The JSON is structurally broken—unclosed brackets, trailing commas, unquoted keys, or single-quote strings—but the intended field names and values are still recognizable. Guardrail: Validate with a strict parser before and after repair; measure field preservation rate, not just parseability.

02

Bad Fit: Semantic Drift

Avoid when: The model output is valid JSON but contains wrong field names, incorrect types, or hallucinated values. Structural repair won't fix semantic errors. Guardrail: Route to schema-mismatch or type-coercion repair prompts instead; structural repair is only for broken syntax.

03

Required Inputs

You must provide: The malformed JSON string, the expected schema or a sample of valid output, and a field-preservation threshold. Guardrail: Without a schema reference, the repair prompt may guess field types incorrectly. Always supply a target shape to validate against.

04

Operational Risk: Silent Data Loss

Risk: A repair prompt that produces valid JSON may drop fields, truncate arrays, or collapse nested objects without warning. Guardrail: Run a field-count diff between input and output; log any field loss above 0% as a repair failure requiring human review.

05

Latency and Cost Sensitivity

Risk: Repairing large or deeply nested JSON payloads can consume significant tokens and add latency to real-time pipelines. Guardrail: Set a max token budget for repair attempts; if the payload exceeds threshold, escalate to a batched offline repair job rather than blocking the hot path.

06

Streaming and Partial Payloads

Avoid when: You're receiving a streaming response that hasn't completed yet. Repairing a partial JSON chunk will produce false positives. Guardrail: Buffer the complete response or use a continuation prompt to request the missing portion before attempting structural repair.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt with square-bracket placeholders for repairing malformed JSON into valid, parseable output.

This template is the core repair instruction you paste into your application's retry or post-processing step after a JSON parse failure. It is designed to be self-contained: provide the broken JSON string and the expected structural constraints, and the prompt instructs the model to return only the repaired, valid JSON. The placeholders let you adapt it to different schemas, failure modes, and risk tolerances without rewriting the core logic.

text
You are a JSON repair system. Your only job is to fix structural errors in malformed JSON and return valid, parseable JSON.

## Input
Below is a JSON string that failed to parse. It may contain unclosed brackets, trailing commas, unquoted keys, single-quoted strings, or other structural errors.

[INPUT]

## Expected Output Schema
Repair the JSON so it conforms to this schema:
[OUTPUT_SCHEMA]

## Constraints
- Return ONLY the repaired JSON. No markdown fences, no explanations, no commentary.
- Preserve all original field values unless they are structurally invalid and cannot be recovered.
- If a required field from the schema is missing and cannot be inferred, insert a null value for that field.
- Do not add fields that are not in the schema.
- Use double quotes for all keys and string values.
- Ensure all brackets and braces are balanced.
- Remove trailing commas.

## Examples
[EXAMPLES]

## Risk Level
[RISK_LEVEL]

To adapt this template, replace each square-bracket placeholder with concrete values for your use case. [INPUT] receives the raw, broken JSON string. [OUTPUT_SCHEMA] should contain a JSON Schema definition, a TypeScript interface, or a plain-text description of required fields and types. [EXAMPLES] is optional but recommended: provide 1-3 pairs of broken-input and repaired-output examples to ground the model's behavior. [RISK_LEVEL] controls the repair aggressiveness. For low-risk data pipelines, instruct the model to infer missing values. For high-risk financial or healthcare records, instruct it to preserve only verifiable fields and nullify anything uncertain. After pasting the completed prompt, always validate the model's output with a JSON parser and a schema validator before allowing the repaired payload to proceed downstream.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the JSON Structure Repair Prompt Template. Each placeholder must be populated before the prompt is sent. Validation notes describe how to confirm the input is ready and what breaks if it is missing or malformed.

PlaceholderPurposeExampleValidation Notes

[MALFORMED_JSON]

The broken JSON string that needs structural repair

{"name": "test", "value": 123,}

Must be a non-empty string. Validate that the input is parseable as a string and not already valid JSON. If already valid, skip repair and return as-is.

[TARGET_SCHEMA]

Optional JSON Schema describing the expected output structure for field-level repair

{"type": "object", "required": ["id", "name"]}

If provided, validate as parseable JSON Schema. If null, the prompt repairs structure only without field coercion. Schema validation errors in the target schema itself must be caught before prompt assembly.

[REPAIR_STRATEGY]

Controls repair aggressiveness: conservative, balanced, or aggressive

balanced

Must be one of: conservative, balanced, aggressive. Conservative refuses ambiguous fixes. Aggressive attempts best-guess repair with logging. Default to balanced if not specified.

[FIELD_PRESERVATION_MODE]

Whether to preserve all original fields or strip fields not in the target schema

preserve_all

Must be one of: preserve_all, strip_extra, or schema_only. strip_extra removes fields not in [TARGET_SCHEMA]. schema_only keeps only schema-defined fields. Default to preserve_all.

[MAX_REPAIR_DEPTH]

Maximum nesting depth for recursive bracket and brace repair

10

Must be a positive integer between 1 and 50. Controls how many levels of unclosed brackets the repair attempts. Higher values risk infinite loops in severely corrupted inputs. Default to 10.

[OUTPUT_FORMAT]

Desired output format: raw_json, indented_json, or compact_json

indented_json

Must be one of: raw_json, indented_json, compact_json. raw_json returns the repaired string without formatting. indented_json pretty-prints with 2-space indent. compact_json removes all non-essential whitespace.

[REPAIR_LOG_LEVEL]

Controls detail level of the repair audit log appended to the response

summary

Must be one of: none, summary, or detailed. none returns only the repaired JSON. summary lists repair actions taken. detailed includes before/after snippets for each fix. Use detailed for debugging, summary for production observability.

[MAX_OUTPUT_TOKENS]

Token budget ceiling for the repair response to prevent truncation of large payloads

4096

Must be a positive integer. Set based on expected output size plus repair log overhead. If the repaired JSON plus log exceeds this, the response may be truncated. Validate against estimated output size before sending.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the JSON Structure Repair prompt into a production application with validation, retries, and observability.

The JSON Structure Repair prompt is designed to sit inside a post-generation repair loop, not as a standalone utility. After your primary model generates a response that fails JSON.parse(), this prompt becomes the first recovery step before escalating to a human or discarding the output. The harness should catch the parse error, extract the raw malformed string, and pass it to the repair prompt with the original expected schema as context. This keeps the repair scope narrow—fixing syntax, not reinterpreting semantics.

Wire the prompt into a retry pipeline with a strict upper bound. A common pattern: attempt JSON.parse() on the raw output; on failure, call the repair prompt once. If the repaired output still fails validation, attempt a second repair pass with the specific parse error message injected into [CONSTRAINTS]. After two repair attempts, log the failure, capture the malformed string and error trace, and either return a structured error to the caller or escalate for human review. Never loop indefinitely—malformed JSON can indicate a deeper model failure that syntax repair cannot fix. For high-throughput systems, add a circuit breaker that stops repair attempts if the failure rate exceeds a threshold within a time window.

Validation must happen in application code, not in the prompt. After the repair prompt returns, run JSON.parse() and then validate against the expected schema using a library like Ajv (JSON Schema), Zod, or Pydantic. Check for: structural validity (parse success), required field presence, correct types, and no extra hallucinated fields. Log the repair_attempt_count, parse_success, schema_valid, and fields_preserved_rate as metrics. For observability, attach the original malformed string, the repaired output, and the validation errors to your trace. This data is essential for detecting whether the repair prompt itself is drifting or whether the upstream model's JSON generation quality is degrading. If your application handles PII or regulated data, ensure the repair prompt runs in the same data boundary as the primary model and that malformed outputs are never logged to unsecured storage.

Model choice matters for repair reliability. Smaller or faster models often struggle with structural repair tasks because they require precise bracket matching and escape character handling. Prefer a capable model with strong code-generation or structured-output performance for the repair step, even if your primary generation uses a smaller model for cost reasons. If latency is critical, consider running the repair prompt in parallel with a second generation attempt from the primary model and taking the first valid result. For streaming applications, buffer the complete response before attempting repair—partial JSON repair is significantly more error-prone and should be handled by a separate continuation or reassembly prompt instead.

IMPLEMENTATION TABLE

Expected Output Contract

The repaired JSON output must conform to this contract. Use these fields, types, and validation rules to verify the repair prompt's output before passing it to downstream systems.

Field or ElementType or FormatRequiredValidation Rule

repaired_json

Valid JSON object or array

JSON.parse must succeed without throwing a SyntaxError. Test with a strict parser.

original_input

String

Must be identical to the [MALFORMED_JSON] input. Verify byte-for-byte equality to ensure no content was dropped.

repair_log

Array of objects

Each element must have 'issue' (string), 'location' (string or null), and 'action' (string). Array must not be empty if any repair was performed.

field_preservation_rate

Number (0.0 to 1.0)

Count of top-level keys in repaired_json divided by count of top-level keys in original_input after parsing. Must be >= 0.95.

structural_validity

Boolean

Must be true. Check that all braces, brackets, and quotes are balanced. No trailing commas. All keys are double-quoted strings.

value_integrity

Object

If present, maps original string values to repaired values. Each entry must show the original and the corrected version. Null if no values were changed.

error_on_repair_failure

String or null

If the repair was impossible, this field contains a structured error message with 'code' and 'description'. Null if repair succeeded.

PRACTICAL GUARDRAILS

Common Failure Modes

JSON structure repair fails in predictable ways. These are the most common failure modes when repairing malformed model outputs, with concrete guardrails to prevent silent data corruption.

01

Silent Field Dropping During Repair

What to watch: The repair prompt removes fields it cannot map to the target schema instead of preserving them in a metadata or overflow container. Critical data disappears without audit trail. Guardrail: Require the prompt to output a preserved_fields audit section listing every input field and its disposition (mapped, dropped, overflow). Validate that input field count equals mapped plus dropped plus overflow count.

02

Type Coercion Producing Wrong Values

What to watch: String-to-number coercion turns "N/A" into 0 or null without flagging the loss. Boolean coercion maps "yes" correctly but "maybe" silently to false. Guardrail: Require the prompt to output a coercion_log array with original value, coerced value, coercion rule applied, and confidence. Add a post-repair validator that rejects coercions below a confidence threshold and routes them for human review.

03

Nested Structure Collapse

What to watch: The repair prompt flattens nested objects incorrectly, overwriting sibling keys when dot-notation collisions occur (e.g., address.city and address both exist). Guardrail: Require the prompt to detect collisions before flattening and output a collision_report. Use a deterministic collision resolution strategy (prefix, namespace, or reject-and-escalate) rather than letting the model choose.

04

Repair Loop Instability

What to watch: A repair prompt applied repeatedly to its own output drifts further from the target schema instead of converging. Each pass introduces new artifacts or drops more fields. Guardrail: Implement a maximum retry count (2-3) with a stability check: compare pre-repair and post-repair outputs. If the delta increases between passes, stop retrying and escalate to a human-reviewed repair queue.

05

Enum Value Guess Gone Wrong

What to watch: The model maps an unknown enum value to the closest canonical value using semantic similarity, but the mapping is incorrect for the domain (e.g., "pending_review" mapped to "approved" instead of "in_progress"). Guardrail: Require an explicit enum mapping dictionary as input. For any value not in the dictionary, the prompt must output null with an unmapped_value flag rather than guessing. Route unmapped values to a human-approved mapping registry.

06

Array Cardinality Mismatch Masking Data Loss

What to watch: The model wraps a single object into an array to satisfy a schema requirement, but when unwrapping later, it silently discards all but the first element of what was actually a multi-item array. Guardrail: Require the prompt to output a cardinality_note for every array field: original element count, wrapped/unwrapped action taken, and final element count. Validate that element count is preserved unless explicitly truncated by a schema constraint.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of a JSON Structure Repair prompt before deploying it into a production pipeline. Use these checks to ensure the prompt reliably fixes structural errors without corrupting valid data.

CriterionPass StandardFailure SignalTest Method

Structural Validity

Output parses successfully with a standard JSON parser (e.g., JSON.parse in Node.js or json.loads in Python).

Parser throws a SyntaxError or JSONDecodeError.

Run output through a JSON parser in a test harness. Assert no exceptions are raised.

Field Preservation Rate

100% of fields present in the valid portion of the malformed input are present in the repaired output.

A field from the input is missing in the output. The count of top-level keys does not match the expected count.

Extract all keys from the input and output using a recursive key walker. Assert the input key set is a subset of the output key set.

Value Integrity

All string, number, boolean, and null values from the input are identical in the output. No values are truncated, re-typed, or hallucinated.

A known value from the input is altered in the output (e.g., a string is truncated, a number is rounded, a boolean is flipped).

Perform a deep comparison of values for all shared keys between the input and output. Assert strict equality.

No Hallucinated Content

The repaired output contains no new keys, values, or structural elements not present in the original malformed input.

A new key-value pair appears in the output that has no source in the input.

Compute the set difference of output keys minus input keys. Assert the difference is an empty set.

Repair of Unclosed Brackets

An input missing a closing }, ], or " is repaired to a valid structure without dropping the unclosed element's content.

The output is valid but the content that followed the unclosed bracket is missing or truncated.

Create a test case with a truncated JSON object. Assert the repaired output contains all key-value pairs from the input.

Repair of Trailing Commas

An input with a trailing comma after the last element in an object or array is repaired to valid JSON.

The output is invalid due to a trailing comma, or the last element is dropped during repair.

Create a test case with a trailing comma. Assert the output parses successfully and the last element is preserved.

Repair of Unquoted Keys

An input with unquoted keys (e.g., {name: "value"}) is repaired to have properly double-quoted keys.

The output is invalid because keys remain unquoted, or a key is incorrectly merged with a value.

Create a test case with unquoted keys. Assert the output parses successfully and all keys are strings.

Repair of Single-Quoted Strings

An input using single quotes for strings is repaired to use double quotes, without altering the string content.

The output is invalid due to single quotes, or an apostrophe inside a string is incorrectly escaped.

Create a test case with single-quoted strings, including one with an internal apostrophe. Assert the output parses and the string content is unchanged.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single model call and no external validation. Focus on getting structurally valid JSON back. Accept that some field values may shift during repair.

code
Repair the following malformed JSON so it is valid and parseable:

[RAW_OUTPUT]

Return only the repaired JSON.

Watch for

  • Missing schema checks—output may be valid JSON but wrong shape
  • Overly broad instructions causing the model to rewrite content instead of repairing structure
  • No logging of what changed during repair
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.