簡體   English   中英

如何在 Python 中以 JSON 的形式訪問對象的對象?

[英]How to access Object of Objects as JSON in Python?

我有 3 節課。

    Class A:
      def __init__(self,a1,a2,a3)
        self.a1 = 10
        self.a2 = B()
        self.a3 =20
    
    Class B:
      def __init__(self,b1,b2,b3)
        self.b1 = C()
        self.b2 = 30
        self.b3 = 40
    
    Class C:
      def __init__(self,c1,c2,c3):
        self.c1 = 50
        self.c2 = 60
        self.c3 = 70

輸入 = [xxx 處的對象 A]

我想獲取對象中的所有詳細信息作為輸出。

輸出應該是 [{a1:10,a2:{b1: {c1:50, c2:60, c3: 70}, b2:30, b3:40}, a3: 20}]

我試過這種方式,但它是忙碌的工作。

for each in input[0].__dict__:
  for x in each.__dict__:

有什么解決辦法嗎? 當然 - 沒有“ValueError:檢測到循環引用”。

在這種情況下,您可能對使用dataclass感興趣

from dataclasses import dataclass

@dataclass
class C:
    c1: int
    c2: int
    c3: int

@dataclass
class B:
    b1: C
    b2: int
    b3: int

@dataclass
class A:
    a1: int
    a2: B
    a3: int

那么例如

>>> c = C(50, 60, 70)
>>> b = B(c, 30, 40)
>>> a = A(10, b, 20)
>>> a
A(a1=10, a2=B(b1=C(c1=50, c2=60, c3=70), b2=30, b3=40), a3=20)

由於使用的方法此對象層次,你可以轉換成一個字典是這樣

>>> import dataclasses
>>> dataclasses.asdict(a)
{'a1': 10, 'a2': {'b1': {'c1': 50, 'c2': 60, 'c3': 70}, 'b2': 30, 'b3': 40}, 'a3': 20}

最后得到一個有效的json字符串

>>> import json
>>> json.dumps(dataclasses.asdict(a))
'{"a1": 10, "a2": {"b1": {"c1": 50, "c2": 60, "c3": 70}, "b2": 30, "b3": 40}, "a3": 20}'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM