Duplicate keys in JSON: what actually happens
A JSON object can legally contain the same key twice. Most developers never expect this, because it almost never happens on purpose, and the result is one of the quieter sources of bugs and security holes in systems that pass JSON between services.
The spec allows it
The JSON grammar defines an object as a comma separated list of name and value pairs. It does not say the names must be unique. So this is syntactically valid JSON:
{
"role": "user",
"role": "admin"
}
Because the grammar permits it, a strict validator will not reject the document. The question of which value wins is left to the parser, and that is where the trouble starts.
What parsers do
The overwhelmingly common behavior is last key wins. The parser builds an object, assigns role to "user", then reaches the second pair and overwrites it with "admin". The first value is silently discarded.
But this is a convention, not a guarantee:
- Most mainstream parsers, including JavaScript's
JSON.parse, keep the last value. - Some keep the first.
- A few raise an error.
- A few preserve both and hand back a non standard structure.
So the same bytes can mean different things to different programs. That divergence is the whole problem.
The security and data loss risks
Two concrete dangers follow from last wins behavior combined with parser disagreement:
- Validation bypass. Imagine a gateway that reads the first
roleto check permissions and forwards the body to a backend that reads the last. Send both keys and you pass the check as auserwhile the backend acts onadmin. This class of parser mismatch has produced real authentication and authorization bypasses. - Silent data loss. If two parts of a system both write into the same object and a key collides, one value vanishes with no error. Nothing warns you, because the document was valid the whole time.
The defense is to treat duplicate keys as malformed input at your trust boundary. Reject any JSON whose top level or nested objects repeat a key, rather than trusting whatever your parser happens to keep.
Finding duplicates
Spotting a repeated key by eye in a large document is hard. Paste the JSON into the JSON Formatter to expand and inspect it; the input stays in your browser, so checking a request body that carries credentials is safe. Reformatting also normalizes the structure so a careful read can catch the collision. For automated defenses, use a parser or schema step that is configured to error on duplicates.
For the broader picture of what strict JSON does and does not permit, see can you use comments in JSON.
The takeaway: duplicate keys are legal JSON but a liability. Assume last wins, never rely on it, and reject repeated keys at any boundary where JSON crosses from one system into another.