【发布时间】:2020-06-06 13:52:34
【问题描述】:
我想通过指定应如何序列化此类实例来序列化自定义类(我无法修改或猴子补丁)。
设置如下:
# some custom class which I cannot modify
class Custom:
def __init__(self, a, b):
self.a = a
self.b = b
# data I want to serialize
data = [Custom(1, 2), Custom(101, 102)]
以下是我对 JSON 的处理方式:
import json
# helper function to handle the custom class
def default(d):
if isinstance(d, Custom):
return dict(a=d.a, b=d.b)
print(json.dumps(data, default=default))
# expected and actual output: [{"a": 1, "b": 2}, {"a": 101, "b": 102}]
我正在努力为 pyyaml 找到等效的解决方案:
import yaml
def yaml_equivalent_of_default():
"YOUR SOLUTION GOES HERE"
print(yaml.dump(data))
# expected output:
# - a: 1
# b: 2
# - a: 101
# b: 102
我尝试了pyyaml docs 中提到的不同方法,但无济于事。
【问题讨论】: