Last active
February 23, 2024 11:03
-
-
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+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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