make a dict/json from string with duplicate keys Python

前端 未结 1 389
迷失自我
迷失自我 2021-01-07 11:43

I have a string that could be parsed as a json or dict object. My string variable looks like this :

    my_string_variable = \"{
                                     


        
相关标签:
1条回答
  • 2021-01-07 12:02

    something like the following can be done.

    import json
    
    def join_duplicate_keys(ordered_pairs):
        d = {}
        for k, v in ordered_pairs:
            if k in d:
               if type(d[k]) == list:
                   d[k].append(v)
               else:
                   newlist = []
                   newlist.append(d[k])
                   newlist.append(v)
                   d[k] = newlist
            else:
               d[k] = v
        return d
    
    raw_post_data = '{"a":1, "b":{"b1":1,"b2":2}, "b": { "b1":3, "b2":2,"b4":8} }'
    newdict = json.loads(raw_post_data, object_pairs_hook=join_duplicate_keys)
    print (newdict)
    

    Please note that above code depends on value type, if type(d[k]) == list. So if original string itself gives a list then there could be some error handling required to make the code robust.

    0 讨论(0)
提交回复
热议问题