jazzband / jsonmodels

jsonmodels is library to make it easier for you to deal with structures that are converted to, or read from JSON.
http://jsonmodels.readthedocs.org/en/latest/
BSD 3-Clause "New" or "Revised" License
334 stars 51 forks source link

ListField does not respect value None (default value is []). #92

Open kashoory opened 6 years ago

kashoory commented 6 years ago

Basically, there is no way to get rid of a ListField element in output json. For other fields, you set them to None and it will be removed from output of to_struct(), but this does not apply to ListField. I reckon, ideally, None value should remove it from json and [] should put a [] in json. It looks like the default value for ListField is [] so there is no way for to_struct() to understand whether user set the field to None, [] or left it unassigned. Also, it looks like 'required' and 'nullable' properties are ignored for ListField.

denisvolokh commented 6 years ago

You can override to_struct method in your model, check all ListFields for len == 0 and skip it like it is doing for None values.

def to_struct(self):

    self.validate()

    resp = {}
    for _, name, field in self.iterate_with_name():
        value = field.__get__(self)
        _type = type(field)
        if value is None or (isinstance(field, fields.ListField) and len(value) == 0):
            continue

        value = field.to_struct(value)
        resp[name] = value

    return resp