コンテンツにスキップ

ClassをJsonにDump

ipynbFile json_dump__ClassをJsonにDump.ipynb

In [1]:

1
import json

In [2]:

1
2
3
class SampleVal:
    hoge : str
    fuga : int

In [3]:

1
2
3
a = SampleVal()
a.hoge = "hoge"
a.fuga = 10

In [11]:

1
2
3
4
class Encoder(json.JSONEncoder):

    def default(self,o):
        return o.__dict__

In [12]:

1
json.dumps(a,cls=Encoder)

Success

1
'{"hoge": "hoge", "fuga": 10}'

最終更新日: 2022-06-15 15:27:00