【问题标题】:How to return json output of object dicts in nested objects?如何在嵌套对象中返回对象字典的 json 输出?
【发布时间】:2020-05-24 08:02:45
【问题描述】:

在一个项目中,我必须为某种实体输出 json 文件。所以这个问题在某种程度上是我问题的简化版本。想象一下,我得到了这些类,我需要它们的 dict 属性和属性作为 json 输出:

from random import randint

class A:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def out_dict(self):
        return self.__dict__

class B:
    def __init__(self, B_a, list_of_A):
        self.b_arg = B_a
        self.list_of_A = list_of_A
    def out_dict(self):
        return self.__dict__

class C:
    def __init__(self, C_a, list_of_B):
        self.c_arg = C_a
        self.list_of_B = list_of_B
    def out_dict(self):
        return self.__dict__

list_of_A = [A(randint(0,100), randint(0,100)) for _ in range(5)]
list_of_B = [B(5, list_of_A) for _ in range(3)]
c = C(10, list_of_B)
print(c.out_dict())

上面代码的输出是:

{'c_arg': 10,
'list_of_B': [<__main__.B at 0x207613625c0>,
 <__main__.B at 0x2076110bdd8>,

如您所见,对象是嵌套的,输出并没有详细提及类的所有属性。另一方面,我需要一些这样的输出:

{"C":
   {"list_of_B":[
    "B0": {
           {"list_of_A":
                {["0":{"a":10, "b":21}, "2":{"a":1, "b":3}, 
                  "1":{"a":10, "b":21}, "2":{"a":54, "b":12},
                  "2":{"a":10, "b":21}, "2":{"a":12, "b":32},
                ]}
            "b_arg": 27
            }


        },
    "B1": {
           {"list_of_A":
                {["0":{"a":10, "b":21}, "2":{"a":1, "b":3}, 
                  "1":{"a":10, "b":21}, "2":{"a":54, "b":12},
                  "2":{"a":10, "b":21}, "2":{"a":12, "b":32},
                ]}
            "b_arg": 27
            }


        },
               ]
    "c_arg": 95
   }
}

在这种情况下如何获取检索详细信息。?

我需要将它们输出为 json。

谢谢

【问题讨论】:

标签: python json oop nested


【解决方案1】:

如果您想拥有相当普通但自定义的对象,它们在层次结构中,但可以将自己转换为 python 类型(整数、字符串、列表和字典)的层次结构,那么您必须安排它们调用 @987654321 @为你递归。

试试这个:

from random import randint

class OutDict:
    def out_dict(self):
        out = {}
        for k,v in self.__dict__.items():
            if hasattr(v,'out_dict'):
                print('out_dict')
                out[k] = v.out_dict()
            elif isinstance(v,list):
                out[k] = self.out_list(v)
            else:
                out[k] = v
        return out

    def out_list(self, values):
        return [v.out_dict() if hasattr(v,'out_dict') else v for v in values]

class A(OutDict):
    def __init__(self, a, b):
        self.a = a
        self.b = b

class B(OutDict):
    def __init__(self, B_a, list_of_A):
        self.b_arg = B_a
        self.list_of_A = list_of_A

class C(OutDict):
    def __init__(self, C_a, list_of_B):
        self.c_arg = C_a
        self.list_of_B = list_of_B

list_of_A = [A(randint(0,100), randint(0,100)) for _ in range(5)]
list_of_B = [B(5, list_of_A) for _ in range(3)]
c = C(10, list_of_B)
print(c.out_dict())

注意我是如何创建一个自定义基类 OutDict 的,它具有 out_dict() 方法(和一个帮助器 out_list() 方法),类 ABC 派生自这些类。

样本输出:

{'c_arg': 10, 'list_of_B': [{'b_arg': 5, 'list_of_A': [{'a': 100, 'b': 93}, {'a': 82, 'b': 52}, {'a': 39, 'b': 63}, {'a': 24, 'b': 94}, {'a': 40, 'b': 95}]}, {'b_arg': 5, 'list_of_A': [{'a': 100, 'b': 93}, {'a': 82, 'b': 52}, {'a': 39, 'b': 63}, {'a': 24, 'b': 94}, {'a': 40, 'b': 95}]}, {'b_arg': 5, 'list_of_A': [{'a': 100, 'b': 93}, {'a': 82, 'b': 52}, {'a': 39, 'b': 63}, {'a': 24, 'b': 94}, {'a': 40, 'b': 95}]}]}

【讨论】:

    【解决方案2】:

    您的核心逻辑是正确的。
    但是问题是您的 list_of_Alist_of_Bc 变量指向您的类,而您最感兴趣的是该类的 out_dict() 方法.
    简单地做类似的事情

    from random import randint
    class A:
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
        def out_dict(self):
            return self.__dict__
    
    class B:
        def __init__(self, B_a, list_of_A):
            self.b_arg = B_a
            self.list_of_A = list_of_A
        def out_dict(self):
            return self.__dict__
    
    class C:
        def __init__(self, C_a, list_of_B):
            self.c_arg = C_a
            self.list_of_B = list_of_B
        def out_dict(self):
            return self.__dict__
    
    list_of_A = [A(randint(0,100), randint(0,100)).out_dict() for _ in range(5)]
    #This                                         ^
    list_of_B = [B(5, list_of_A).out_dict() for _ in range(3)]
    #Solves                     ^
    c = C(10, list_of_B).out_dict()
    #It                 ^
    print(c)
    

    解决问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      相关资源
      最近更新 更多