我正在使用棉花糖将我的决策类实例发送给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
棉花糖开发团队的答案可以在Bugtracker中的此评论中找到:
使用post_dump
方法。
from marshmallow import Schema, fields, post_dump
class BaseSchema(Schema):
SKIP_VALUES = set([None])
@post_dump
def remove_skip_values(self, data, **kwargs):
return {
key: value for key, value in data.items()
if value not in self.SKIP_VALUES
}
class MySchema(BaseSchema):
foo = fields.Field()
bar = fields.Field()
sch = MySchema()
sch.dump({'foo': 42, 'bar': None}).data # {'foo': 42}
正如我在进一步的评论中指出的那样,存在一个缺点:当字段的allow_none
为True
时,它也将删除None
。
正如我在上面的评论中指出的那样,如果您使用
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
}
这适用于我的对象