Inferensys

Prompt

Malformed Contact JSON Repair Prompt Template

A practical prompt playbook for using Malformed Contact JSON Repair Prompt Template in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, the ideal user, and the constraints for the Malformed Contact JSON Repair Prompt Template.

This prompt is for integration engineers and backend developers who receive contact records from an LLM that are semantically correct but structurally broken. The job-to-be-done is repairing a JSON payload that has failed downstream validation due to common model-generated errors: missing required fields, type mismatches (e.g., a phone number stored as an integer), nested structure corruption, or encoding artifacts. The ideal user has a known target schema for a contact object and needs a reliable, automated repair step before the data enters a CRM, CDP, or customer data platform. The required context is the malformed JSON string and the expected schema definition.

Use this prompt when a model's output is close to correct but fails a strict schema validator. It is designed for post-generation repair loops, not for initial structured output generation. If you need the model to produce valid JSON on the first attempt, use a schema-first prompting strategy from the Structured Output and Schema Control pillar instead. This prompt is appropriate when the cost of discarding the output is high, such as in batch processing pipelines where partial failure recovery is critical. It is not a substitute for fixing the root cause of malformed generation in your primary prompt.

Do not use this prompt for repairing outputs that contain hallucinated contact data. If the model invented names, emails, or phone numbers, this prompt will faithfully coerce them into a valid schema, creating a dangerous false positive. For hallucination issues, use the Contact Record Hallucination Detection Prompt Template from this pillar first. Additionally, if the malformed JSON contains PII that should not be logged or processed, ensure your pipeline redacts sensitive fields before they reach this repair step. The next section provides the copy-ready template you can adapt with your specific schema and coercion rules.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and what you must provide before using it in a production pipeline.

01

Good Fit: Post-Generation Repair

Use when: A model has already produced a contact JSON payload that failed schema validation. This prompt is a repair step, not a primary generation strategy. Guardrail: Always run strict schema validation before invoking repair to avoid unnecessary LLM calls.

02

Bad Fit: Real-Time User-Facing Chat

Avoid when: Latency is critical and the user is waiting. Repair loops add seconds. Guardrail: For chat, use structured output modes (JSON mode, tool calling) upfront. Reserve this prompt for async or batch pipelines where correctness beats speed.

03

Required Input: The Original Broken Payload

Risk: Without the malformed input, the prompt has nothing to repair. Guardrail: Pass the exact broken JSON string, including any error messages from your validator, as context. Never ask the model to guess what was broken.

04

Required Input: The Target Schema

Risk: The model may hallucinate fields or use incorrect types if the schema is ambiguous. Guardrail: Provide a strict JSON Schema or a clear field specification with types, required flags, and enum values. Vague instructions produce vague repairs.

05

Operational Risk: Silent Data Corruption

Risk: The model might "repair" a field by inventing a plausible value (e.g., guessing a missing email domain) instead of marking it as null. Guardrail: Instruct the prompt to use null or a specific sentinel for unrecoverable fields. Post-repair, validate that no fields were hallucinated by comparing against the original input.

06

Operational Risk: Repair Loop Escalation

Risk: A single repair attempt may fail, leading to infinite retry loops that waste tokens and delay pipelines. Guardrail: Implement a maximum retry count (e.g., 2 attempts). If validation still fails, log the record for human review and route it to a dead-letter queue instead of retrying indefinitely.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for repairing malformed contact JSON payloads with schema validation and field coercion rules.

This prompt template is designed to be dropped into a repair loop after your primary model generates a contact JSON that fails validation. It accepts the broken payload, the expected schema, and a set of coercion rules, then returns a repaired object that conforms to your downstream contract. The template uses square-bracket placeholders so you can inject the specific inputs your application already has—no manual rewriting required.

text
You are a contact record repair system. Your job is to take a malformed or invalid contact JSON object and repair it so that it strictly conforms to the provided schema and coercion rules.

## INPUT
[MALFORMED_JSON]

## EXPECTED SCHEMA
[EXPECTED_SCHEMA]

## COERCION RULES
[COERCION_RULES]

## CONSTRAINTS
- Do not invent or hallucinate values for fields that are missing and cannot be inferred from the input. Use null for missing optional fields and flag required fields that cannot be repaired.
- If a field value is present but has the wrong type, coerce it according to the coercion rules. If coercion is impossible, set the field to null and add an entry to the repair_log.
- Normalize all identifiers (email, phone, URL) according to the rules specified in the coercion rules.
- Remove any fields that are not present in the expected schema.
- If the input contains nested objects that should be flattened, flatten them according to the schema.
- If the input is truncated or contains encoding artifacts, repair what you can and flag what you cannot.

## OUTPUT FORMAT
Return a valid JSON object with exactly two top-level keys:
- "repaired_contact": the repaired contact object conforming to the expected schema
- "repair_log": an array of objects, each describing one repair action taken, with fields: "field", "original_value", "repaired_value", "action" (one of: coerced, defaulted, removed, inferred, could_not_repair), and "reason"

## EXAMPLES
[REPAIR_EXAMPLES]

Repair the input now.

Adapting the template: Replace [MALFORMED_JSON] with the broken payload your model produced. [EXPECTED_SCHEMA] should contain your target JSON schema with field names, types, and required/optional markers. [COERCION_RULES] is where you specify type conversion rules (e.g., "string to number: strip non-numeric characters and parse"), normalization rules for identifiers, and field-specific defaults. [REPAIR_EXAMPLES] should include 2-3 before/after pairs showing correct repair behavior for common failure modes in your pipeline. If your contact schema is large, consider splitting the coercion rules into a separate reference block and referencing it by name to keep the prompt manageable. Always test with at least 20 known-broken examples before wiring this into a production repair loop.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Malformed Contact JSON Repair prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to verify the input is correct before execution.

PlaceholderPurposeExampleValidation Notes

[MALFORMED_JSON]

The broken contact JSON payload that needs repair

{"name": "Jane", "email": "jane@test", "phone": 5551234567}

Must be a non-empty string. Parse attempt should fail or produce unexpected types. If already valid JSON, skip repair and return as-is.

[TARGET_SCHEMA]

JSON Schema describing the expected output structure

{"type": "object", "properties": {"full_name": {"type": "string"}, "email_address": {"type": "string", "format": "email"}}, "required": ["full_name", "email_address"]}

Must be a valid JSON Schema object. Validate with a schema validator before use. Required fields must be marked. Include type constraints and format keywords.

[FIELD_COERCION_RULES]

Rules for converting mismatched types to correct types

{"phone": "string", "age": "integer", "is_active": "boolean"}

Map of field names to target types. Supported types: string, integer, number, boolean, array, object. Null values allowed if field is optional. Missing fields will use default coercion: stringify numbers, parse numeric strings.

[REQUIRED_FIELDS]

List of fields that must be present in the output

["full_name", "email_address", "phone_number"]

Array of field name strings. Must be a subset of TARGET_SCHEMA properties. If a required field cannot be repaired, set to null and flag in repair notes. Empty array means no required fields.

[NULL_HANDLING]

Policy for handling missing or unrecoverable fields

set_null_and_flag

Must be one of: set_null_and_flag, omit_field, use_default, or fail_repair. set_null_and_flag is recommended for downstream validation. fail_repair aborts and returns original input with error.

[ENCODING_REPAIR]

Whether to attempt fixing encoding corruption and escape characters

Boolean. When true, the prompt will attempt to fix unicode escapes, double-encoding, invalid escape sequences, and invisible whitespace. Set false if encoding is known clean to reduce token usage.

[MAX_REPAIR_DEPTH]

Maximum nesting depth for nested object repair

3

Integer between 1 and 10. Controls how many levels of nested objects the repair prompt will attempt to fix. Deeper nesting increases token usage and repair time. Default is 3 for contact records.

[OUTPUT_FORMAT]

Expected output format for the repaired contact

json_object

Must be one of: json_object, json_array, or json_lines. json_object returns a single repaired record. json_array wraps single record in array. json_lines returns newline-delimited JSON for batch processing.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the malformed contact JSON repair prompt into a production application with validation, retries, and safe defaults.

This prompt is designed to sit inside a post-generation repair loop, not as a standalone service. The typical integration pattern is: (1) receive a model-generated contact JSON payload, (2) validate it against your target schema, (3) if validation fails, invoke this repair prompt with the original payload and the validation error details, (4) validate the repaired output, and (5) either accept it, retry, or escalate. Do not call this prompt on every output—only on outputs that fail schema validation. This keeps latency and cost low for the majority of clean responses.

Validation harness: Before calling the repair prompt, run the raw output through a JSON schema validator (such as ajv for JavaScript, jsonschema for Python, or your API gateway's schema enforcement layer). Capture the specific validation errors—missing required fields, type mismatches, pattern violations, and unexpected keys. Pass these errors into the [VALIDATION_ERRORS] placeholder as structured text. The repair prompt uses these errors to target its fixes rather than guessing what's broken. After receiving the repaired output, run the same validator again. If the output still fails, increment a retry counter and include the new errors in the next repair attempt.

Retry and escalation logic: Implement a bounded retry loop—typically 2-3 attempts maximum. On each retry, include the accumulated validation errors and the previous repair attempt in the [PREVIOUS_ATTEMPTS] placeholder so the model can see what it already tried. If the output still fails after the retry budget, escalate to a human review queue rather than silently accepting a broken record. For high-volume pipelines, log the failure with the original payload, all repair attempts, and the final validation errors. This log becomes your dataset for improving the prompt or identifying systemic model failure patterns.

Model choice and temperature: Use a model with strong JSON generation and instruction-following capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent). Set temperature=0 or very low (0.0-0.1) to maximize deterministic repair behavior. This is not a creative task—you want the model to apply mechanical fixes, not invent alternative contact representations. If your pipeline uses a smaller or faster model for initial generation, it's acceptable to route repair calls to a more capable model since repair volume should be a small fraction of total traffic.

Field coercion rules and safe defaults: The prompt includes a [COERCION_RULES] placeholder where you define how to handle ambiguous fields. For example: "If phone is a number type, convert it to a string with E.164 formatting. If email contains spaces, remove them. If name is null but first_name and last_name exist, construct name from the components." Define these rules based on your downstream system's tolerance. Never allow the model to invent missing required fields—if email is required and absent, the repair should flag it as null or a sentinel value like "MISSING_REQUIRED_FIELD" rather than guessing. Your application layer should decide whether to reject, enrich, or accept records with missing required fields.

Logging and observability: Instrument every repair call with the original payload hash, validation error count, repair attempt number, and final outcome (success, retry, escalation). This data feeds your prompt observability dashboard and helps you detect drift—for example, if repair rates suddenly spike from 2% to 15% of outputs, your upstream model or input data may have changed. Track the most common validation errors being repaired; if the same field breaks repeatedly, consider improving your initial generation prompt or adding pre-processing rather than relying on post-hoc repair.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the exact fields, types, and validation rules for the repaired contact JSON object. Use this contract to build a post-processing validator that rejects any output not conforming to these rules.

Field or ElementType or FormatRequiredValidation Rule

contact_id

string (UUID v4)

Must match UUID v4 regex. If missing or invalid, generate a new one and log a warning.

full_name

string

Must be non-empty after trimming. If null or empty, set to 'Unknown' and flag for human review.

email

string (RFC 5322)

If present, must pass RFC 5322 regex. If malformed, attempt repair; if repair fails, set to null and add to [repair_log].

phone

string (E.164)

If present, must match E.164 pattern. Strip non-digit characters, infer country code from [default_country_code] if missing, else set to null.

address

object

If present, must contain at least one non-empty child field. If empty object, set to null.

address.street

string

Trim whitespace. If only whitespace, set to null.

address.city

string

Trim whitespace. If only whitespace, set to null.

address.postal_code

string

Trim whitespace. If only whitespace, set to null.

repair_log

array of strings

Must be an array. Append a message for every field coercion, type fix, or null fallback applied. Cannot be null.

PRACTICAL GUARDRAILS

Common Failure Modes

When repairing malformed contact JSON, these failures surface first in production. Each card identifies a specific breakage pattern and the guardrail that catches it before downstream systems reject the payload.

01

Silent Field Dropping on Partial Repair

What to watch: The model repairs the first structural error it encounters, then stops—leaving later fields missing or truncated without warning. The output looks valid JSON but is incomplete. Guardrail: Add a post-repair field completeness check that compares the output field set against the expected schema and flags any missing required fields for a second repair pass or human review.

02

Type Coercion That Destroys Meaning

What to watch: The model aggressively coerces a malformed field into the expected type—converting a corrupted phone number string into null, or a partial date into 1970-01-01. The output passes schema validation but the data is semantically destroyed. Guardrail: Run a value-range and semantic sanity check after repair. Flag nulls where the original field had content, and reject default timestamp values that match Unix epoch or other sentinel defaults.

03

Nested Object Collapse into Flat Fields

What to watch: When the model encounters a broken nested structure (e.g., a corrupted address object), it flattens the fields into the parent object or drops the nesting entirely. contact.address.street becomes contact.street, breaking downstream parsers. Guardrail: Validate the output against the exact JSON Schema, not just type checks. Reject outputs where the nesting depth or key paths differ from the expected structure, and re-prompt with the schema inline.

04

Hallucinated Repair Values from Context Starvation

What to watch: When a field is entirely missing or unreadable, the model invents plausible values from its training data rather than leaving the field empty or flagging it. You get a valid-looking email like john.doe@example.com that never existed in the input. Guardrail: Require the model to output a repair_confidence field for each repaired value. Route low-confidence repairs to a human review queue, and never auto-accept invented contact identifiers.

05

Encoding Corruption Surviving Repair

What to watch: The model fixes JSON structure but passes through invisible encoding artifacts—zero-width characters, smart quotes masquerading as ASCII, or double-encoded UTF-8 sequences. These break database inserts and API clients that expect clean strings. Guardrail: Run a character-level sanitizer after repair that normalizes Unicode, strips control characters, and replaces smart quotes with ASCII equivalents. Test with a known-corrupted payload in your eval suite.

06

Array Field Unwrapping on Single Element

What to watch: When a malformed array contains only one element, the model sometimes unwraps it into a single object. phone_numbers: [{...}] becomes phone_numbers: {...}, which passes some lenient parsers but breaks strict downstream code expecting an array. Guardrail: Enforce array cardinality in the post-repair validator. If the schema says type: array, reject any output where that field is an object—even if it contains the data. Re-prompt with explicit array syntax examples.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the Malformed Contact JSON Repair prompt before shipping. Each row defines a pass standard, a failure signal, and a concrete test method to catch regressions early.

CriterionPass StandardFailure SignalTest Method

Schema Compliance

Output passes JSON Schema validation for the target contact object (all required fields present, no additional properties unless allowed).

Validation error: missing required field, type mismatch, or extra field present.

Run output through jsonschema.validate() against the canonical contact schema. Assert no ValidationError is raised.

Field-Level Type Coercion

String fields like [PHONE] are correctly coerced to string type; numeric fields like [AGE] are coerced to integer; boolean fields like [IS_ACTIVE] are coerced to boolean.

TypeError on field access: phone is integer, age is string, or is_active is string 'true'.

Assert isinstance(output['phone'], str), isinstance(output['age'], int), isinstance(output['is_active'], bool) for a set of 20 malformed inputs.

Nested Structure Repair

Nested objects (e.g., [ADDRESS]) are correctly promoted from flat keys or repaired from broken nesting.

KeyError when accessing output['address']['street'] because address is a string or flat keys like address_street remain.

Assert output['address'] is dict and output['address']['street'] exists for inputs where address fields were flattened or stringified.

Encoding Artifact Removal

Output contains no mojibake, unescaped control characters, or double-encoded sequences.

Presence of replacement characters (\ufffd), literal \n strings, or double-escaped quotes.

Parse output with json.loads. Assert no UnicodeDecodeError and no \ufffd in any string value. Check for literal backslash-n.

Null vs. Empty String Handling

Missing optional fields are set to null; present but empty fields remain empty strings. No confusion between the two.

Optional field missing from input appears as empty string '', or present empty field becomes null.

For input with 'nickname': '' and no 'title' field, assert output['nickname'] == '' and output['title'] is None.

Hallucinated Field Removal

Output contains only fields derivable from the input. No invented email, phone, or address fields.

Output includes a valid-looking email or phone number not present in the malformed input.

Diff the set of output keys against the set of input keys. Assert no new top-level keys appear that weren't in the input or explicitly required by the schema with a null default.

Array Normalization

Fields expecting arrays (e.g., [TAGS]) are always arrays, even if input provides a comma-separated string or single value.

TypeError when iterating over tags because it's a string.

Assert isinstance(output['tags'], list) for inputs where tags is 'tag1, tag2' or 'singletag'.

Idempotency

Passing already-valid JSON through the repair prompt produces identical output (no drift or unnecessary rewriting).

Valid input is reformatted, reordered, or has fields added/removed.

Provide a perfectly valid contact JSON. Assert output == input after normalizing key order and whitespace.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base repair prompt but relax strict schema enforcement. Use a simpler output contract: request valid JSON with corrected fields without requiring a specific schema library. Accept that some type coercion may be imperfect.

code
You are a JSON repair assistant. Fix the following malformed contact JSON.
Return ONLY valid JSON with these fields corrected:
- name (string)
- email (string)
- phone (string)

Malformed input:
[INPUT]

Watch for

  • Missing field coercion rules leading to inconsistent types
  • Overly broad instructions that hallucinate missing fields
  • No validation loop—bad outputs pass through silently
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.