Serializing dict of nested schema at the top level
See original GitHub issueHi all,
I am using marshmallow 3.0.0b16
. I am trying to write a REST endpoint that wants to return a json dictionary of objects. The python signature looks something like:
class Foo():
def __init__(a: str, b: int):
pass
def myEndpoint() -> Dict[str, Foo]:
return { "a": Foo("a", 1), "b": Foo("b", 2) }
The FooSchema
is pretty trivial to write, however when I want to write the schema for the dict, I found I have to wrap it with another top level object in order to get to dump correctly.
class FooDictSchema(Schema):
foo_dict = fields.Dict(key=field.String(), value=field.Nested(FooSchema))
This works for dumping but injects an unnecessary "foo_dict"
key at the top level of the json object, when I tried doing schema = FooSchema(many=true)
and dumping the dict, i get a bunch of empty values.
Is there an easy way to dump a dictionary directly where it uses a nested type? This is very similar to the following issue: https://github.com/marshmallow-code/marshmallow/issues/483 but my usecase requires the nested dict to be at the top level.
Issue Analytics
- State:
- Created 5 years ago
- Comments:18 (5 by maintainers)
Top GitHub Comments
Hi @sloria, sorry to necromance on this closed issue, but isn’t the
from_dict
a rather resource heavy approach? I know it solves the problem, but if I understand it well, it creates a disposable schema with N fields for N keys in the dictionary, right? Seems more like a workaround than a solution.I understand working directly with a
dict
might not fit in the whole marshmallow concept ofSchema
s being objects, but I think one could pretty easily use theserialize
/deserialize
interface of the field directly. I’ve developed a little example how this could work:The output is as expected:
The
accessor
forserialize
is a little hacky, but one could wrap that to adump
/load
method just for theDict
field. Maybe 😃I don’t think this addresses one of the earlier requirements, which was for a dictionary with unknown keys (issue #120):
https://github.com/marshmallow-code/marshmallow/issues/120
Was there ever any progress made on supporting that use case? I continue to use my own NamedObjectMap field (which i show in #120) but I would much rather use something that is officially maintained.