Advertisement
haiv

Detect duplicate keys in JSON

Oct 1st, 2014
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. import json
  2. import collections
  3.  
  4. json_string = """
  5. {
  6.    "a": 1,
  7.    "a": 2,
  8.    "b": [1,2,3],
  9.    "b": "foo",
  10.    "c": {"x":1, "y":2, "z":3, "a":4}
  11. }
  12. """
  13.  
  14. def detect_duplicate_keys(list_of_pairs):
  15.     key_count = collections.Counter(k for k,v in list_of_pairs)
  16.     duplicate_keys = ', '.join(k for k,v in key_count.items() if v>1)
  17.  
  18.     if len(duplicate_keys) != 0:
  19.         raise ValueError('Duplicate key(s) found: {}'.format(duplicate_keys))
  20.  
  21. def validate_data(list_of_pairs):
  22.     detect_duplicate_keys(list_of_pairs)
  23.     # More dectection, each of them will raise exception upon invalid
  24.     # data
  25.     return list_of_pairs
  26.  
  27.  
  28. obj = json.loads(json_string, object_pairs_hook=validate_data)
  29. print obj
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement