Skip to content

Instantly share code, notes, and snippets.

@DavidBuchanan314
Last active February 23, 2024 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidBuchanan314/bf57251b2519c5ea55042fc4af62e033 to your computer and use it in GitHub Desktop.
Save DavidBuchanan314/bf57251b2519c5ea55042fc4af62e033 to your computer and use it in GitHub Desktop.
How to ensure JSON has no duplicate map keys in Python 3.1+
from typing import List, Tuple, Any
import json
def ensure_no_duplicate_keys(object_pairs: List[Tuple[str, Any]]) -> dict:
value = dict(object_pairs)
if len(value) != len(object_pairs):
raise ValueError("Duplicate JSON map keys")
return value
if __name__ == "__main__":
# The problem: this code "works", but silently ignores first entry
print(json.loads('{"a": "123", "a": "xyz"}'))
# This works entirely as expected, there are no duplicate keys here
print(json.loads('{"a": "123", "b": "xyz"}', object_pairs_hook=ensure_no_duplicate_keys))
# raises ValueError
print(json.loads('{"a": "123", "a": "xyz"}', object_pairs_hook=ensure_no_duplicate_keys))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment