Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask Marshmallow JSON fields

I have defined a POST call would that needs data:

{
    "one" : "hello",
    "two" : "world",
    "three" : { 
                "ab": "123", 
                "cd": false 
              }
}

For this, I am able to define one and two, but unsure what is the right was to define three. How can I specify a JSON field in Marshmallow? I am able to define basic fields such as:

from marshmallow import Schema, post_load, fields

class Foo(object):
    def __init__(self, one, two=None):
        self.one = one
        self.two = two

class MySchema(Schema):
    one = fields.String(required=True)
    two = fields.String()

    @post_load
    def create_foo(self, data, **kwargs):
        return Foo(**data)

How do I define three in MySchema? Should I:

  1. simply put it as a string and do manipulation to load it as a json using json.loads()/json.dumps()? Or is there a way to define it properly?
  2. define it as a fields.Dict?
  3. can I define a separate Schema for this field
  4. should I extend field.Field?

I am looking at https://marshmallow.readthedocs.io/en/3.0/api_reference.html, though still not sure. A JSON sub-field or a nested JSON seems like a common use-case, yet I am not able to find anything relevant on this.

like image 640
rgamber Avatar asked Mar 30 '19 22:03

rgamber


1 Answers

This can be done with nested schemas: https://marshmallow.readthedocs.io/en/3.0/nesting.html

Your schema would look something like:

class MySchema(Schema):
    one = fields.String(required=True)
    two = fields.String()
    three = fields.Nested(ThreeSchema)

class ThreeSchema(Schema):
    ab = fields.String()
    cd = fields.Boolean()
like image 144
jspcal Avatar answered Oct 31 '22 04:10

jspcal