在编写 API 时,我经常需要像这样从嵌套 JSON 初始化类
# When my API receives such a ...
n_json = {"nested1": {"nested2" : { "nested3" : "..." }}}
# .. I need to instantiate a proper object out of it ...
nested1 = Nested1.from_json(json.loads(n_json))
# ... so I can later use the instance in OOP style.
nested1.nested2.run_an_intance_method()
在我的代码中,这会导致级联
class Nested1:
@classmethod
def from_json(json):
self.nested2=Nested2.from_json(json.nested2)
随着每一层嵌套,这会变得更加重复且容易出错。有什么巧妙的方法可以做到这一点吗?
最佳答案
这就是如何从 JSON 创建嵌套对象(类似于 PHP 的做法)。要从 JSON(更确切地说,解析的 JSON,它只是一个 Python 结构)创建对象树,请编写以下类:
class Nested:
def __new__(cls, structure):
self = super(Nested, cls).__new__(cls)
if type(structure) is dict:
self.__dict__ = {key: Nested(structure[key]) for key in structure}
elif type(structure) is list:
self = [Nested(item) for item in structure]
else:
self = structure
return self
并从解析后的 JSON 中调用它。例如:
import json
s = json.dumps({'a': 1, 'b': {'c': [1, 2, {'d': 3}], 'e': {'f': 'g'}}})
result = Nested(json.loads(s))
print(result.a) # 1
print(result.b.c) # [1, 2, <__main__.Nested object at 0x00000297A983D828>]
print(result.b.c[0]) # 1
print(result.b.c[2].d) # 3
<小时/>
以下是该类的工作原理:
__new__
在其他任何事情之前被调用。这里我们构造一个对象的实例(空)如果 new 是列表,我们将 self 替换为嵌套对象列表,因此
Nested({'a': [1, 2, 3]).a
等于[Nested(1), Nested(2), Nested(3)]
(也等于[1, 2, 3]
,参见数字 4)如果 new 是 dict,则为每个键创建一个具有相同名称的属性,并为其分配
Nested(dict[key])
。如果是任何其他类型,只需为 self 赋值(将
self
替换为 value),以便Nested({'a': ['b', 'c', 'd']}).a[0]
等于'b'
,而不是Nested(..)
关于python - 在 Python 中从 JSON 初始化嵌套类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39151488/