Using JSON keys as attributes in nested JSON

前端 未结 3 586
失恋的感觉
失恋的感觉 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:16

    I think you're making this more complex than it needs to be. If I understand you correctly, all you should need to do is this:

    import json
    
    class Struct(dict):
        def __getattr__(self, name):
            return self[name]
    
        def __setattr__(self, name, value):
            self[name] = value
    
        def __delattr__(self, name):
            del self[name]
    
    j = '{"y": [2, 3, {"a": 55, "b": 66}], "x": 4}'
    
    aa = json.loads(j, object_hook=Struct)
    
    for i in aa.y:
        print(i)
    

    When you load JSON, the object_hook parameter lets you specify a callable object to process objects that it loads. I've just used it to turn the dict into an object that allows attribute access to its keys. Docs

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-02-06 06:31

    I found the answer: There is intentionally no way to automatically map the special methods in python, using __getattribute__. So to achieve what I want, I need to explicitely define all special methods like __len__ one after the other.

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