2023/04/02 05:43 編集
※ 削除
投稿2023/04/02 05:08
フィールドに他クラスのインスタンスを持つクラスのjsonファイル出力
Pythonで以下のようなクラスA,Bがあるときに,クラスAの__dict__をダンプしようとすると
フィールドにクラスBがありObject型であるためにエラーが発生してしまします.
クラスA.__dict__をしたときに,フィールドのクラスBも.__dict__で処理できればよいのですが方法がわかりません.
Traceback (most recent call last): File "test.py", line 17, in <module> json.dumps(a.__dict__) File "Python39\lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "Python39\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "Python39\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "Python39\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type B is not JSON serializable
python
1import json 2 3class A: 4 def __init__(self, a, b): 5 self.data_a = a 6 self.class_b = b 7 8class B: 9 def __init__(self, b): 10 self.data_b = b 11 12b = B('b') 13a = A('a', b) 14json.dumps(a.__dict__)
13行目の引数をb.__dict__にすればいいのですが,
python内部ではクラスオブジェクトのまま保持したいです.
よろしくお願いします.
回答2件
あなたの回答
tips
プレビュー