Last active
September 3, 2023 19:56
-
-
Save htv2012/ad8c19ac43e128aa7ee1 to your computer and use it in GitHub Desktop.
How to detect duplicate keys when decoding JSON string
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
import json | |
import collections | |
json_string = """ | |
{ | |
"a": 1, | |
"a": 2, | |
"b": [1,2,3], | |
"b": "foo", | |
"c": {"x":1, "y":2, "z":3, "a":4} | |
} | |
""" | |
def detect_duplicate_keys(list_of_pairs): | |
key_count = collections.Counter(k for k,v in list_of_pairs) | |
duplicate_keys = ', '.join(k for k,v in key_count.items() if v>1) | |
if len(duplicate_keys) != 0: | |
raise ValueError('Duplicate key(s) found: {}'.format(duplicate_keys)) | |
def validate_data(list_of_pairs): | |
detect_duplicate_keys(list_of_pairs) | |
# More dectection, each of them will raise exception upon invalid | |
# data | |
return dict(list_of_pairs) | |
obj = json.loads(json_string, object_pairs_hook=validate_data) | |
print obj |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exactly what I was looking for. Thank you!