json.loads allows duplicate keys in a dictionary, overwriting the first value

前端 未结 4 1617
自闭症患者
自闭症患者 2020-11-27 18:54
>>> raw_post_data = request.raw_post_data
>>> print raw_post_data
{\"group\":{\"groupId\":\"2\", \"groupName\":\"GroupName\"}, \"members\":{\"1\":{         


        
4条回答
  •  失恋的感觉
    2020-11-27 19:26

    Alternatively if you want to catch all the duplicate keys (per level) you can use a collections.Counter

    from collections import Counter
    
    class KeyWatcher(dict):
    
        def __init__(self, *args):
            duplicates = [d for d,i in Counter([pair[0] for pair in args[0]]).items() if i > 0]
            if duplicates:
                raise KeyError("Can't add duplicate keys {} to a json message".format(duplicates))
            self.update(*args[0])
    
    json.loads(raw_post_data, object_pairs_hook=KeyWatcher)
    

提交回复
热议问题