使用棉花糖进行JSON序列化-跳过None属性

时间:2019-03-11 19:04:28

标签: json python-3.x serialization marshmallow

我正在使用棉花糖将我的Decision类的实例发送到JSON。但是,这也会转储None的属性,例如我的属性score将在JSON中转换为null。之后,我无法使用相同的方法再次读取JSON。

https://repl.it/repls/VoluminousMulticoloredFacts

最后一行是当前失败的地方。我不需要将None转储到JSON或在加载过程中跳过null

import json
from marshmallow import Schema, fields, post_load

json_data = """{
    "appid": "2309wfjwef",
    "strategy": "First Strategy"
}"""

# Output class definition
class Decision(object):
    def __init__(self, appid = None, strategy = None, score = None):
        self.appid = appid
        self.strategy = strategy
        self.score = score

class DecisionSchema(Schema):
    appid = fields.Str()
    strategy = fields.Str()
    score = fields.Int()

    @post_load
    def make_decision(self, data):
        return Decision(**data)

# Deserialization into object
dec_json = json.loads(json_data)
schema = DecisionSchema()
dec = schema.load(dec_json).data

print(dec.strategy)

# Dump results back to JSON
schema = DecisionSchema()
out = schema.dumps(dec)

print(out.data)

# Load back from dump
schema = DecisionSchema()
dec = schema.load(out).data

#print(dec.strategy) # returns error currently

1 个答案:

答案 0 :(得分:0)

正如我在上面的评论中所指出的,如果您使用

class Meta:
    fields = (
        'field1', 'field2
    )
    ordered = True

要解决此问题,我使用了此方法:

# Remove None fields
@pre_dump
def remove_skip_values(self, data):
    return {
        key: value for key, value in data.items()
        if value is not None
    }

这适用于我的对象字典