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

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

    One alternative I wrote based on the solution posted by other users of this question is to convert those duplicates into an array:

    def array_on_duplicate_keys(ordered_pairs):
        """Convert duplicate keys to arrays."""
        d = {}
        for k, v in ordered_pairs:
            if k in d:
                if type(d[k]) is list:
                    d[k].append(v)
                else:
                    d[k] = [d[k],v]
            else:
               d[k] = v
        return d
    

    And then:

    dict = json.loads('{"x": 1, "x": 2}', object_pairs_hook=array_on_duplicate_keys)
    

    gives you the output:

    {'x': [1, 2]}
    

    Later one, one can check easily how meany duplicates an entry has by using:

    if type(dict['x']) is list:
        print('Non-unique entry in dict at x, found', len(dict['x']),'repetitions.')
    

提交回复
热议问题