Using JSON keys as attributes in nested JSON

前端 未结 3 585
失恋的感觉
失恋的感觉 2021-02-06 06:07

I\'m working with nested JSON-like data structures in python 2.7 that I exchange with some foreign perl code. I just want to \'work with\' these nested structures of lists and

3条回答
  •  既然无缘
    2021-02-06 06:24

    There is an attrdict library that does exactly that in a very safe manner, but if you want, a quick and dirty (possibly leaking memory) approach was given in this answer:

    class AttrDict(dict):
        def __init__(self, *args, **kwargs):
            super(AttrDict, self).__init__(*args, **kwargs)
            self.__dict__ = self
    
    j = '{"y": [2, 3, {"a": 55, "b": 66}], "x": 4}'
    aa = json.loads(j, object_hook=AttrDict)
    

提交回复
热议问题