我已经定义了一个需要数据的 POST 调用:
{
"one" : "hello",
"two" : "world",
"three" : {
"ab": "123",
"cd": false
}
}
为此,我可以定义 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)
我如何定义 three
在 MySchema
?我是不是该:json.loads()/json.dumps()
将其加载为 json ?或者有没有办法正确定义它? 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()
关于python - flask 棉花糖 JSON 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55436043/