JSON Errors / All languages
Duplicate keys in JSON: which value wins?How to Fix: Duplicate keys in JSON: which value wins?
A JSON object with the same key twice - {"a": 1, "a": 2} - is not a syntax error in most parsers: the spec says object names "SHOULD be unique" but does not forbid duplicates. Nearly every mainstream parser silently keeps the last occurrence and discards earlier ones.
That silent data loss is the danger: no exception, no warning, just a value that disappeared. Duplicate keys have even been used in security exploits, where a validation layer reads the first occurrence while the execution layer reads the last.
Common causes
1. Hand-edited config files
Adding a setting without noticing it already exists further up the file. The earlier value silently stops applying.
{
"timeout": 30,
...50 lines...
"timeout": 5
}2. Merging JSON with string concatenation
Combining two documents by splicing text instead of merging parsed objects produces duplicates when both sides define the same key.
3. Generators emitting the same field twice
Serializers fed from case-insensitive sources (e.g. HTTP headers) or buggy template-based JSON generation.
How to fix it
import json
def reject_duplicates(pairs):
seen = {}
for key, value in pairs:
if key in seen:
raise ValueError(f"Duplicate key: {key!r}")
seen[key] = value
return seen
data = json.loads(text, object_pairs_hook=reject_duplicates)// Go's json.Unmarshal takes the last occurrence, no error.
// To reject duplicates, walk tokens with json.Decoder:
dec := json.NewDecoder(strings.NewReader(text))
// iterate dec.Token() and track keys per object depthFrequently asked questions
Which value do the major languages actually keep?
Last occurrence wins in JavaScript (JSON.parse), Python (json.loads), Go, PHP, Ruby, and Jackson in Java. Some strict parsers and linters (and Gson's tree model in some modes) flag duplicates. Never rely on either behavior - treat duplicates as a bug in the producer.
Why are duplicate keys a security concern?
When two systems read the same document with different duplicate-handling (first-wins vs last-wins), an attacker can craft a payload that passes validation in one layer but does something different in another - this pattern has appeared in real vulnerabilities in API gateways and JWT libraries. Consistent parsing plus duplicate rejection closes the gap.
How do I find duplicates in a big JSON file?
Use a parse-time hook like Python's object_pairs_hook (example above), a linter like jsonlint --strict, or paste the document into the validator on this page after sorting keys - adjacent duplicates become easy to spot. Standard parsers cannot report them after parsing because the duplicate is already gone.
Last updated:
Related JSON errors
You might also need
Free and in-browser, like everything on JSON Console. Browse all tools →