question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Clarification on using fields.Dict()

See original GitHub issue

Suppose I want to serialize a dict with complex objects, each with their own Schema, like:

class Inner():
    a = "testing"
    b = "123"
class InnerSchema(Schema):
    a = fields.Str()
    b = fields.Str()

class Outer():
    c = {}

Then populate it, like

o = Outer()
o.c['one'] = Inner()
o.c['two'] = Inner()

What I’d like the serialization to look like is something like:

{ 
"c": {
    "one": {"a": "testing", "b": "123"},
    "two": {"a": "testing", "b": "123"}
    }
}

What is the schema for class Outer? This gives an error trying to serialize the Inner objects:

class OuterSchema(Schema):
    c = fields.Dict(fields.Nested(InnerSchema, many=True))

or, also the same error:

class OuterSchema(Schema):
    c = fields.Dict(fields.Nested(InnerSchema),  many=True)

Is this possible with fields.Dict in Marshmallow? I have seen things like #424, #120, #258, it seems like it is possible with the new fields.Dict, but here it looks like the Nested is not propagating the Inner schema to the serializer.

TypeError: <__main__.Inner object at 0x7f9673300be0> is not JSON serializable

Thanks!

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
sloriacommented, Apr 15, 2016

fields.Dict does not take an inner field as an argument; it does not apply any special formatting on serialization.

However, it would be easy enough to implement:

class ComposableDict(fields.Dict):

    def __init__(self, inner, *args, **kwargs):
        self.inner = inner
        super().__init__(*args, **kwargs)

    def _serialize(self, value, attr, obj):
        return {
            key: self.inner._serialize(val, key, value)
            for key, val in value.items()
        }

Then use it like so:

class Inner():
    a = "testing"
    b = "123"

class Outer():
    c = {}

class InnerSchema(Schema):
    a = fields.Str()
    b = fields.Str()

class OuterSchema(Schema):
    c = ComposableDict(fields.Nested(InnerSchema))

o = Outer()
o.c['one'] = Inner()
o.c['two'] = Inner()

sch = OuterSchema()
print(sch.dump(o).data)
# {'c': {'one': {'a': 'testing', 'b': '123'}, 'two': {'a': 'testing', 'b': '123'}}}
0reactions
seeb0hcommented, Jun 26, 2018

Right. I just test new implementation from https://github.com/marshmallow-code/apispec/issues/201 and it is much better.

Test with 3.0.0b11 + apispec 0.38

Read more comments on GitHub >

github_iconTop Results From Across the Web

Marshmallow: Dict of nested Schema - Stack Overflow
Show activity on this post. I'm wondering how to serialize a dict of nested Schema . Serializing a list of Schema can be...
Read more >
How to use the marshmallow.fields.Dict function in ... - Snyk
Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately. ... Dict(), allow_none=True) service_account =...
Read more >
Dictionaries in Python - Real Python
In this Python dictionaries tutorial, you'll cover the basic characteristics and learn how to access and manage dictionary data. Once you have finished...
Read more >
Python Dictionary (With Examples) - Programiz
In this tutorial, you'll learn about Python dictionaries; how they are created, accessing, adding, removing elements from them and various built-in methods.
Read more >
Excel VBA Dictionary - A Complete Guide
A Dictionary is similar to a Collection. Using both types, we can name an item when we add it. Imagine we are storing...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found