我定义了一个需要数据的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.DictSchema吗?field.Field吗?我在看reference.html,虽然还不确定。JSON子字段或嵌套JSON似乎是一个常见的用例,但我无法找到与此相关的任何东西。
发布于 2019-03-30 22:13:21
这可以通过嵌套模式来完成: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()发布于 2021-04-15 11:36:17
您可以创建自己的字段。
import json
from marshmallow import fields
class JSON(fields.Field):
def _deserialize(self, value, attr, data, **kwargs):
if value:
try:
return json.loads(value)
except ValueError:
return None
return None...
from marshmallow import fields, Schema
from schemas.base import JSON
class ObjectSchema(Schema):
id = fields.Integer()
data = JSON()发布于 2021-06-26 11:10:04
如果希望在字段中支持任意嵌套值,而不是为其定义架构,则可以使用:
fields.Dict() (接受任意Python对象,或等效的任意dict对象),或fields.Raw() (用于任意Python对象,或等效的任意JSON值)可以根据问题中的示例运行使用上述两种方法的示例脚本:
import json
from marshmallow import Schema, fields, post_load
class Foo(object):
def __init__(self, one, two=None, three=None, four=None):
self.one = one
self.two = two
self.three = three
self.four = four
class MySchema(Schema):
one = fields.String(required=True)
two = fields.String()
three = fields.Dict()
four = fields.Raw()
@post_load
def create_foo(self, data, **kwargs):
return Foo(**data)
post_data = json.loads(
"""{
"one" : "hello",
"two" : "world",
"three" : {
"ab": "123",
"cd": false
},
"four" : 567
}"""
)
foo = MySchema().load(post_data)
print(foo.one)
print(foo.two)
print(foo.three)
print(foo.four)https://stackoverflow.com/questions/55436043
复制相似问题