代码之家  ›  专栏  ›  技术社区  ›  Mario

使用python访问json子有效负载

  •  -1
  • Mario  · 技术社区  · 7 年前

    我有一个这样的班级:

    class Payload(object):
       def __init__(self, payload__):
           self.__dict__ = json.loads(payload__)
    

    我可以这样读取JSON有效负载:

    json = Payload('{"Test1":"Test2","Test3":{"Test4":true}}')
    

    所以我可以获得 Test 就像这样:

    print(json.Test1) # result: Test2
    

    但我无法获得 Test4 它是 Test3

    print(json.Test3.Test4) #result: AttributeError: 'dict' object has no attribute 'Test4'
    

    所以,错误是 AttributeError: 'dict' object has no attribute 'Test4'

    任何帮助都将不胜感激。

    谢谢!

    3 回复  |  直到 7 年前
        1
  •  0
  •   Mario    7 年前

    我已经解决了!

    感谢@stack链接到 Accessing dict keys like an attribute? 有两种不同的方法来解决我的问题:

    1. 使用 json.Test3['Test4']
    2. 使用类:

      class AttributeDict(dict):
          def __getattr__(self, attr):
              return self[attr]
          def __setattr__(self, attr, value):
              self[attr] = value
      

    顺便说一下,我发现第一种方法更简单。

    我现在可以访问 Test4 就像这样:

    print(json.Test3['Test4'])
    
        2
  •  0
  •   ItayBenHaim    7 年前

    尝试使用:

    print(json["Test3"]["Test4"])
    
        3
  •  0
  •   Tryph    7 年前

    如果您没有被使用dict符号(使用方括号)而不是点符号所干扰,那么您可以简单地避免使用有效负载类,并以这种方式访问dict中的每个数据:

    payload = json.loads('{"Test1":"Test2","Test3":{"Test4":true}}')
    print(payload['Test1'])  # "Test2
    print(payload['Test3']['Test4']) # "True
    

    但是,如果您想使用点符号访问每个数据,可以使用 AttrDict 来自的类 this answer 并提供给 the object_hook parameter of the json.loads method . 这使得 json 模块使用提供的类而不是 dict 要将JSON对象映射到Python对象,请执行以下操作:

    import json
    
    
    class AttrDict(dict):
        def __init__(self, *args, **kwargs):
            super(AttrDict, self).__init__(*args, **kwargs)
            self.__dict__ = self
    
    
    payload = json.loads(
        '{'
        '  "key_1": "pouet",'
        '  "key_2": {'
        '    "key_21": true,'
        '    "key_22": {'
        '      "key_221": "toto"'
        '    }'
        '  }'
        '}',
        object_hook=AttrDict)
    
    
    print(payload.key_1)  # "pouet"
    print(payload.key_2.key_21)  # True
    print(payload.key_2.key_22.key_221) # "toto"
    

    请注意,有效负载类也是无用的。