Using JSON keys as attributes in nested JSON

前端 未结 3 596
失恋的感觉
失恋的感觉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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

提交回复
热议问题