Using colander 1.5.1, if I pass null
to an attribute defined by a nested schema:
class ChildSchema(colander.Schema):
a = colander.SchemaNode(colander.Integer(), missing=None)
b = colander.SchemaNode(colander.Integer(), missing=None)
class ParentSchema(colander.Schema):
c = colander.SchemaNode(colander.Integer(), missing=None)
d = ChildSchema(missing=None)
example json:
{
"c": 1,
"d": null
}
Then I get this error when deserialising:
"\"None\" is not a mapping type: Does not implement dict-like functionality."
Not passing the attribute d
functions as expected, and deserialises to None
. How do I correctly handle deserialising a null
value passed to a nested schema? I would expect the behaviour to return None
, based on the documentation.
Deserialization Combinations
Please consider the following:
You need the following imports.
Below is the same as your Child Schema.
Below is where all the magic occurs. We create our own type. Note that it may lack some of the basic functionalities that the built-ins in colander SchemaTypes may offer (like serialize). If the recieved object is null or None then it is returned with not changes. If it is not null or None and not a dictionary it will raise an error, and if it is a dictionary it will be serialized with your ParentSchema, even if the attributes of the Parent are null or None ({"d": null}).
We create the Parent Schema using the magic type:
"d" will be deserialize as u wish. Now lets see some examples of its usage:
Example 1. "d" is null (The main question)
Output 1
Example 2. "d" is None
Output 2
Example 3. Normal behaviour
Output 3.
Example 5. Error "d" is not dict
Output 5
Example 6. Error validator not number
Output 6
To write this answer I used https://docs.pylonsproject.org/projects/colander/en/latest/extending.html as a source.