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

前端 未结 4 1626
自闭症患者
自闭症患者 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:40

    The rfc 4627 for application/json media type recommends unique keys but it doesn't forbid them explicitly:

    The names within an object SHOULD be unique.

    From rfc 2119:

    SHOULD This word, or the adjective "RECOMMENDED", mean that there
    may exist valid reasons in particular circumstances to ignore a
    particular item, but the full implications must be understood and
    carefully weighed before choosing a different course.

    import json
    
    def dict_raise_on_duplicates(ordered_pairs):
        """Reject duplicate keys."""
        d = {}
        for k, v in ordered_pairs:
            if k in d:
               raise ValueError("duplicate key: %r" % (k,))
            else:
               d[k] = v
        return d
    
    json.loads(raw_post_data, object_pairs_hook=dict_raise_on_duplicates)
    # -> ValueError: duplicate key: u'1'
    

提交回复
热议问题