rga*_*ber 6 python marshmallow
我已经定义了一个需要数据的 POST 调用:
{
"one" : "hello",
"two" : "world",
"three" : {
"ab": "123",
"cd": false
}
}
Run Code Online (Sandbox Code Playgroud)
为此,我能够定义one和two,但不确定定义three. 如何在 Marshmallow 中指定 JSON 字段?我能够定义基本字段,例如:
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)
Run Code Online (Sandbox Code Playgroud)
我如何定义threein MySchema?我是不是该:
json.loads()/json.dumps()? 或者有没有办法正确定义它?fields.Dict?Schema为这个字段定义一个单独的吗field.Field吗?我正在查看https://marshmallow.readthedocs.io/en/3.0/api_reference.html,但仍然不确定。JSON 子字段或嵌套的 JSON 似乎是一个常见的用例,但我找不到任何与此相关的内容。
这可以通过嵌套模式完成:https : //marshmallow.readthedocs.io/en/3.0/nesting.html
您的架构看起来像:
class MySchema(Schema):
one = fields.String(required=True)
two = fields.String()
three = fields.Nested(ThreeSchema)
class ThreeSchema(Schema):
ab = fields.String()
cd = fields.Boolean()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5034 次 |
| 最近记录: |