This prompt is for integration engineers and backend developers who receive model-generated JSON objects containing duplicate keys—a common hallucination pattern where a model repeats a field name with different values inside the same object. The job-to-be-done is straightforward: take a malformed JSON object, apply a resolution strategy, and return a clean single-key object with an audit trail showing what was merged or discarded. You need this when your pipeline ingests JSON from LLMs, downstream parsers reject or silently overwrite duplicate keys, and you cannot control the model's output format at generation time.
Prompt
Duplicate Key Resolution Prompt for JSON Objects

When to Use This Prompt
Define the job, reader, and constraints for the Duplicate Key Resolution Prompt.
Use this prompt when you have a specific JSON object that failed parsing or validation due to duplicate keys, and you need a deterministic repair before the payload enters your application logic. The ideal user has the raw model output, knows which resolution strategy applies—LAST_WINS, MERGE_VALUES, or FLAG_CONFLICT—and can feed both into the prompt. Do not use this prompt for general JSON repair (missing commas, bracket imbalances), for schema validation failures, or for objects where duplicate keys are intentional in a non-JSON context. This is a targeted surgical tool, not a general-purpose JSON fixer.
Before wiring this into production, define your resolution strategy per field. LAST_WINS is safest for idempotent values where later occurrences override earlier ones. MERGE_VALUES works when duplicate keys should combine into arrays or concatenated strings. FLAG_CONFLICT is appropriate for high-risk fields where automated resolution is unsafe and human review is required. You should also decide whether the merge audit—the record of what was changed—gets logged, stored alongside the output, or discarded. In regulated workflows, keep the audit trail for traceability. Next, copy the prompt template and adapt the placeholders to your object structure and resolution policy.
Use Case Fit
Where the Duplicate Key Resolution Prompt works, where it fails, and the operational conditions required before you wire it into a production pipeline.
Good Fit: Post-Validation Repair Loop
Use when: A JSON parser or schema validator rejects the model output specifically because of duplicate keys. The prompt sits inside a repair loop after initial generation fails. Guardrail: Only invoke this prompt after a parse error is caught; do not run it on every response.
Bad Fit: Streaming or Partial Payloads
Avoid when: The JSON is still arriving as a stream or the payload is truncated. Duplicate key detection on incomplete structures produces false positives. Guardrail: Buffer and validate the complete payload before triggering the resolution prompt.
Required Input: Resolution Strategy
Risk: Without an explicit [RESOLUTION_STRATEGY], the model guesses whether to merge values, keep the last occurrence, or flag the conflict. Guessing leads to silent data loss. Guardrail: Always pass a strategy enum (MERGE, LAST_WINS, FLAG) and include it in the prompt template as a non-negotiable parameter.
Required Input: Merge Audit Trail
Risk: The downstream consumer cannot tell which keys were duplicated or how they were resolved, making debugging impossible. Guardrail: Require the prompt to output a merge_audit array alongside the cleaned object, listing each duplicate key, the conflicting values, and the resolution applied.
Operational Risk: Semantic Collision
Risk: Two keys are identical but represent different semantic fields (e.g., a nested object key vs. a top-level metadata key). A mechanical merge corrupts the data model. Guardrail: Pair this prompt with a schema-aware validator that checks the cleaned output against the expected structure before accepting it.
Operational Risk: Large Object Performance
Risk: Running duplicate key resolution on very large JSON objects (100K+ keys) burns tokens and latency without adding value if duplicates are rare. Guardrail: Pre-scan the raw string for duplicate key patterns with a lightweight regex check; only invoke the LLM repair prompt when duplicates are detected.
Copy-Ready Prompt Template
A reusable prompt for resolving duplicate keys in JSON objects using a configurable strategy, with a merge audit trail.
This prompt template is designed to be copied directly into your application's prompt layer. It instructs the model to accept a JSON object containing duplicate keys—a common hallucination pattern in model-generated structured output—and resolve them according to a specified strategy. The prompt requires the malformed JSON input and a resolution strategy, and it produces a clean, single-key object along with a structured audit of every merge decision made.
textYou are a precise JSON repair system. Your task is to resolve duplicate keys in a JSON object. ## INPUT You will receive a JSON object that may contain duplicate keys. This is the object to repair: ```json [INPUT_JSON]
RESOLUTION STRATEGY
Apply the following strategy to resolve each set of duplicate keys: [RESOLUTION_STRATEGY]
Where [RESOLUTION_STRATEGY] is one of:
LAST_WINS: Keep only the last occurrence of the key and its value. Discard all earlier occurrences.MERGE_VALUES: Combine all values for the duplicate key into a JSON array. The order of values in the array must match the order of occurrence in the original object.FLAG_CONFLICT: Replace the value with a conflict marker object{"__conflict__": true, "values": [<all values in order>]}and append an entry to the audit log.
OUTPUT SCHEMA
Return a valid JSON object with exactly two top-level keys:
repaired_object: The JSON object with all duplicate keys resolved. No keys are duplicated.merge_audit: An array of objects, each describing one resolution. Each object has:key: The duplicate key that was resolved.strategy_applied: The strategy used (LAST_WINS,MERGE_VALUES, orFLAG_CONFLICT).original_occurrences: The number of times the key appeared.kept_value: The final value assigned to the key inrepaired_object.discarded_values: An array of values that were discarded or merged (empty forLAST_WINSwhen only one value is kept).
CONSTRAINTS
- Do not modify any key names or values except as required by the resolution strategy.
- Do not reorder keys in the repaired object; preserve the original key order, using the position of the first occurrence for merged or flagged keys.
- The output must be strictly valid JSON with no trailing commas, no comments, and no markdown fences.
- If the input contains no duplicate keys, return the object unchanged and an empty
merge_auditarray.
To adapt this template, replace [INPUT_JSON] with the malformed payload from your model's output. Since standard JSON parsers will reject or silently drop duplicate keys, you must capture the raw text response before parsing. Set [RESOLUTION_STRATEGY] to the strategy that matches your downstream tolerance: use LAST_WINS for simple API payloads where the last value is likely the correction, MERGE_VALUES when all occurrences may carry distinct data (e.g., multiple tags or categories), and FLAG_CONFLICT when ambiguity requires human review. After receiving the model's response, validate that repaired_object parses successfully and that every key in merge_audit corresponds to an actual duplicate in the input. If the model fails to produce valid JSON, retry with stricter formatting instructions or fall back to a deterministic post-processing script.
Prompt Variables
Required inputs for the Duplicate Key Resolution Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to verify the input is well-formed before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[INPUT_JSON] | The JSON string or object containing duplicate keys that must be resolved | {"id": 1, "name": "alpha", "name": "beta"} | Parse check: must be valid JSON or parseable JSON string. If unparseable, route to JSON Repair Prompt first. |
[RESOLUTION_STRATEGY] | Specifies how duplicate key conflicts are resolved: MERGE_VALUES, LAST_WINS, FIRST_WINS, or FLAG_CONFLICT | LAST_WINS | Enum check: must be one of MERGE_VALUES, LAST_WINS, FIRST_WINS, FLAG_CONFLICT. Reject unknown strategies before prompt assembly. |
[OUTPUT_SCHEMA] | JSON Schema describing the expected output structure, including the merge_audit field contract | {"type": "object", "required": ["resolved_object", "merge_audit"]} | Schema check: must be valid JSON Schema draft-07 or later. Validate with ajv or equivalent before passing to prompt. |
[CONFLICT_THRESHOLD] | Maximum number of duplicate key conflicts allowed before the prompt escalates to human review instead of auto-resolving | 5 | Range check: integer between 1 and 100. If conflict count exceeds threshold, skip resolution and return FLAG_CONFLICT escalation payload. |
[MERGE_STRATEGY_DETAIL] | For MERGE_VALUES strategy, specifies how values are combined: CONCATENATE, ARRAY_AGGREGATE, or DEEP_MERGE for nested objects | ARRAY_AGGREGATE | Enum check: required only when RESOLUTION_STRATEGY is MERGE_VALUES. Must be CONCATENATE, ARRAY_AGGREGATE, or DEEP_MERGE. Null allowed for other strategies. |
[CONTEXT] | Optional description of the JSON's origin and downstream use, helping the model decide edge cases like intentional duplicates versus hallucinations | Customer record from CRM export with duplicate email fields due to merge conflict | Null allowed. If provided, should be plain text under 500 characters. Longer context degrades prompt precision on the structural task. |
Implementation Harness Notes
How to wire the Duplicate Key Resolution prompt into a production application with validation, retries, and audit logging.
The Duplicate Key Resolution prompt is designed to sit inside a post-generation repair loop—after a model produces JSON but before that JSON reaches a downstream parser, database, or API client. Most JSON parsers will either reject duplicate keys outright or silently keep only the last occurrence, which means the model's intent is lost without a controlled resolution step. This harness intercepts the raw model output, detects duplicate keys via a pre-pass scanner, and only invokes the LLM repair prompt when duplicates are actually present. This avoids unnecessary latency and cost for clean outputs.
Wire the prompt into your application as a conditional repair stage. First, parse the raw model output string with a streaming JSON scanner that tracks key occurrences without full deserialization. If no duplicate keys are detected, pass the output through unchanged. If duplicates are found, construct the prompt with the full raw JSON string as [INPUT_JSON] and the chosen strategy (MERGE_VALUES, KEEP_LAST, KEEP_FIRST, or FLAG_CONFLICT) as [RESOLUTION_STRATEGY]. The model returns a JSON object with two fields: resolved_json (the clean single-key object) and merge_audit (an array of objects documenting each duplicate key, the conflicting values, and the resolution action taken). Validate the response by confirming resolved_json parses without errors and contains no duplicate keys. If validation fails, retry once with the validation error message appended as additional context. After two failures, log the incident and route to a human review queue rather than looping indefinitely.
For model choice, prefer a fast, instruction-following model with strong JSON output discipline—GPT-4o-mini or Claude 3.5 Haiku work well for this bounded task. Set temperature=0 to maximize deterministic behavior, since duplicate key resolution should follow the stated strategy consistently. The merge_audit field is critical for observability: persist it alongside the resolved JSON so that downstream consumers and auditors can see exactly what the repair stage changed. In high-stakes pipelines (financial records, healthcare data, legal documents), require a human to approve any resolution where FLAG_CONFLICT was the strategy or where the audit shows value-level conflicts that couldn't be cleanly merged. Never silently drop conflicting data without an audit trail.
Expected Output Contract
The resolved JSON object must conform to this contract. Validate each field after the repair prompt completes.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
resolved_object | object | Must be a valid JSON object parseable by JSON.parse or equivalent. Must not contain duplicate keys. | |
resolved_object.* | any | All keys must be unique strings. No duplicate keys permitted in the final output. | |
merge_audit | object | Must contain a 'strategy' field matching the provided [RESOLUTION_STRATEGY] value and a 'resolved_keys' array. | |
merge_audit.strategy | string | Must exactly match one of: 'merge_values', 'last_wins', 'first_wins', 'flag_conflict'. Enum validation required. | |
merge_audit.resolved_keys | array | Array of objects, each with 'key' (string), 'occurrences' (integer >= 2), 'action' (string), and 'original_values' (array). | |
merge_audit.resolved_keys[].key | string | Must match a key that appeared more than once in the input object. Non-empty string. | |
merge_audit.resolved_keys[].occurrences | integer | Must be >= 2. Must equal the count of times the key appeared in the input. | |
merge_audit.resolved_keys[].action | string | Must be one of: 'merged', 'kept_last', 'kept_first', 'conflict_flagged'. Must align with the strategy used. | |
merge_audit.resolved_keys[].original_values | array | Must contain all values associated with the duplicate key in order of appearance. Length must equal occurrences. | |
unresolved_conflicts | array | If present, each element must have 'key' (string), 'reason' (string), and 'values' (array). Only expected when strategy is 'flag_conflict'. | |
validation_warnings | array | If present, each element must be a non-empty string describing a non-blocking issue encountered during resolution. |
Common Failure Modes
When resolving duplicate keys in model-generated JSON, these failures surface first in production. Each card pairs a common breakage pattern with a concrete guardrail you can implement before shipping.
Silent First-Value Retention
What to watch: The model resolves duplicate keys by keeping the first occurrence and discarding later values without warning. Critical data in later duplicates is lost silently, and the merge audit shows no conflict. Guardrail: Always require an explicit [RESOLUTION_STRATEGY] parameter. If the strategy is 'first-wins', include a mandatory audit field listing every discarded key-value pair with its position in the original object.
Deep Merge on Nested Objects
What to watch: The model treats duplicate keys as a signal to recursively merge nested objects instead of replacing at the key level. This produces a Frankenstein object combining fields from both occurrences that no downstream system expects. Guardrail: Add a [MERGE_DEPTH] constraint set to 'shallow' by default. Explicitly instruct the model that duplicate keys trigger replacement at the current level only, never recursive merging, unless [MERGE_DEPTH] is explicitly set to 'deep'.
Array Concatenation Without Deduplication
What to watch: When duplicate keys hold arrays, the model concatenates them without checking for duplicate elements. Repeated runs compound the problem, producing bloated arrays with redundant entries. Guardrail: When [RESOLUTION_STRATEGY] is 'merge-arrays', include a [DEDUPLICATE_ARRAYS] boolean flag. Default it to true and require the model to apply Set-like deduplication on primitive values or ID-based deduplication on objects before concatenation.
Type Collision on Conflicting Values
What to watch: Duplicate keys hold values of different types—one occurrence has a string, the other an object. The model picks one arbitrarily or coerces both into a string, breaking downstream type contracts. Guardrail: Add a [TYPE_CONFLICT_POLICY] parameter with options 'prefer-first-type', 'prefer-last-type', or 'flag-as-conflict'. When 'flag-as-conflict' is selected, the output must include a type_conflicts array documenting each collision with original types and positions.
Positional Blindness in Large Objects
What to watch: In objects with hundreds of keys, the model misses duplicate keys that are far apart in the input. It produces a clean output that still contains duplicates because it never detected the conflict. Guardrail: Pre-process the input with a deterministic duplicate detector before sending to the model. Include a detected_duplicates preamble in the prompt listing every duplicate key and its occurrence positions, forcing the model to acknowledge and resolve each one explicitly.
Audit Trail Omission Under Token Pressure
What to watch: When the input is large and approaching token limits, the model skips generating the merge audit to save tokens. You lose traceability on which duplicates were resolved and how. Guardrail: Reserve a fixed token budget for the audit output by specifying a [MAX_AUDIT_SIZE] constraint. If the audit would exceed this budget, instruct the model to summarize conflicts by key name only rather than omitting the audit entirely. Validate audit presence in the post-processing harness.
Evaluation Rubric
Use this rubric to evaluate the quality of the model's output for the Duplicate Key Resolution Prompt before integrating it into a production pipeline. Each criterion should be tested with a representative set of malformed JSON inputs.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Duplicate Key Resolution | All duplicate keys are resolved according to the specified [RESOLUTION_STRATEGY] (e.g., MERGE, LAST_WINS). No duplicate keys remain in the final output. | Duplicate keys persist in the output object. A value was selected that violates the stated strategy. | Parse the output JSON and compare the list of keys against the input. Verify the resolved value matches the strategy for each conflict. |
Output JSON Validity | The output string is strictly valid JSON that can be parsed by a standard | The output is not parseable JSON. It contains trailing commas, unquoted strings, or a trailing merge audit block outside the JSON structure. | Execute |
Non-Duplicate Key Preservation | All keys that were not duplicated in the input object are present in the output object with their original values completely unchanged. | A non-duplicate key is missing, renamed, or its value has been altered or re-typed. | Perform a deep comparison of all non-duplicate key-value pairs between the parsed input and the parsed output. |
Merge Audit Completeness | The output contains a separate | The | Validate the |
Data Integrity Under Resolution | No data is silently dropped during a MERGE strategy. For LAST_WINS, the correct value is selected. String values are not truncated or corrupted. | A value from a duplicate key is missing from a merged array. A string value is cut off. The wrong duplicate is chosen for LAST_WINS. | For MERGE, verify all original values are concatenated. For LAST_WINS, verify the final value is an exact match for the last occurrence in the input. |
Instruction Adherence | The model follows all constraints, such as outputting only the JSON object with no markdown fences or explanatory text before or after. | The output is wrapped in markdown code fences ( | Check the raw output string. The first non-whitespace character must be |
Hallucination Resistance | The model does not invent new keys, add extra fields to the resolved object, or fabricate a merge audit for a clean input with no duplicates. | A new key like | Provide a valid JSON input with no duplicate keys. The output must be identical to the input, with an empty or absent |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with [RESOLUTION_STRATEGY] set to last_wins and skip the merge audit output. Accept the cleaned object without validation beyond a basic parse check.
code[RESOLUTION_STRATEGY]: last_wins [OUTPUT_SCHEMA]: Return only the cleaned JSON object. No audit trail.
Watch for
- Silent data loss when the model picks the wrong duplicate value
- No visibility into which keys were duplicated or how they were resolved
- Strategy drift where the model applies a different resolution than instructed

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us