Marshmallow - turn None string to empty string

Viewed 4560

I receive an email body with some strings that are None instead of "".

I have tried using missing, default, allow_none, and other hacks I found online but nothing works.

I want to turn None to "" in my schema. I thought a simple email = fields.String(missing = "") would work, but I guess None does not count as missing.

Schema:

class CustomerSchema(Schema):
    @post_dump
    def change_none_to_string(self, data, **kwargs):
        for field in data:
            if data[field] is None:
                data[field] = ""
        return data

    firstname = fields.String(missing = "")
    lastname = fields.String(missing = "")
    email = fields.String(missing = "")
1 Answers

You can use a post-dump or pre-load function to change things in your input or output before processing, for instance adding:

@post_dump
def change_none_to_string(self, data, **kwargs)
    for field in data:
        if data[field] is None:
            data[field] = ""
    return data

to your schema should mean that your output has all of the None fields replaced with "", and you can do a similar thing with pre-load for input.

Assuming your input is raw text in json (it might not be, I haven't seen your input), this should do the job, but it depends on exactly how your input is formatted:

@pre_dump
def change_none_to_string_input(self, data, **kwargs):
    for field in data:
        data[field] = data[field].replace("null", '""')
    return data

Check https://marshmallow.readthedocs.io/en/stable/extending.html for more detail on that.

Related