【问题标题】:Serializing custom classes with pyyaml使用 pyyaml 序列化自定义类
【发布时间】: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 中提到的不同方法,但无济于事。

【问题讨论】:

    标签: python pyyaml


    【解决方案1】:

    我相信如果可以腌制自定义类成员/字段,这应该可以工作:

    import yaml
    
    class Custom:
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
    data_to_serialize = [Custom(1, 2), Custom(101, 102)]
    
    def yaml_equivalent_of_default(dumper, data):
        dict_representation = data.__dict__
        node = dumper.represent_dict(dict_representation)
        return node
    
    yaml.add_representer(Custom, yaml_equivalent_of_default)
    
    print(yaml.dump(data_to_serialize))
    

    输出:

    - a: 1
      b: 2
    - a: 101
      b: 102
    

    representer 的签名是def add_representer(data_type, representer, Dumper=Dumper),因此可以将Damper 传递给它。所有可用的倾销者都是['BaseDumper', 'SafeDumper', 'Dumper']

    【讨论】:

    • 我怎么会错过Dumper 部分?谢谢@QuirkyBit!
    猜你喜欢
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    相关资源
    最近更新 更多