我想用marshmallow
验证嵌套请求JSON,我几乎遵循了它的文档来验证我的请求JSON数据。经过几次尝试,我认为使用棉花糖来验证复杂的JSON数据是正确的方法。然而,我从棉花糖中得到了一个验证错误,如下所示:
更新的错误消息
> PS C:Usersjysonimmunomatch_api> python .json_validation.py
> Traceback (most recent call last): File ".json_validation.py", line
> 58, in <module>
> app = schema.load(app_data) File "C:UsersjysonAppDataLocalProgramsPythonPython37libsite-packagesmarshmallowschema.py",
> line 723, in load
> data, many=many, partial=partial, unknown=unknown, postprocess=True File
> "C:UsersjysonAppDataLocalProgramsPythonPython37libsite-packagesmarshmallowschema.py",
> line 904, in _do_load
> raise exc marshmallow.exceptions.ValidationError: {'_schema': ['Invalid input type.']}
更新
之前我出现了位置参数错误,因为我隐式定义了def __init__(self, age, gender, features)
等功能,而不是在definit中执行硬代码(self、age、gender、IL10、CRP(。为什么我会有以上错误?有什么想法吗?感谢
我尝试使用棉花糖进行json验证:
from marshmallow import Schema, fields, post_load
from marshmallow import EXCLUDE
import json
class Feature(object):
def __init__(self, value, device):
self.value = value
self.device= device
class FeatureSchema(Schema):
value = fields.Str()
device= fields.Str()
@post_load
def make_feature(self, data, **kwargs):
return Feature(**data)
class App(object):
def __init__(self, age, gender, features):
self.age = age
self.gender = gender
self.features = features
class AppSchema(Schema):
age = fields.Str()
gender = fields.Str()
features = fields.Nested(FeatureSchema)
@post_load
def make_app(self, data, **kwargs):
return App(**data)
json_data = """{
"body": {
"gender": "M",
"PCT4": {
"value": 12,
"device": "roche_cobas"
},
"IL10": {
"value": 12,
"device": "roche_cobas"
},
"CRP": {
"value": 12,
"device": "roche_cobas"
},
"OM10": {
"value": 120,
"device": "roche_bathes"
}
}
}"""
app_data = json.loads(json_data)
schema = AppSchema(unknown=EXCLUDE, many=TRUE)
app = schema.load(app_data)
print(app.data.features.value)
为什么我会出现上述错误?验证嵌套JSON的正确方法是什么?为什么我有未知的字段错误?有任何可能的想法来消除上面的错误吗?感谢
错误明确提到问题
marshmallow.exceptions.ValidationError: {'OM10': ['Unknown field.'], 'CRP': ['Unknown field.'], 'IL10': ['Unknown field.'], 'PCT4': ['Unknown field.']}
Marshmallow的模式不理解该字段,因为您尚未将其声明到模式中,默认情况下,如果发现Unknown Field
,Marshmallow将引发错误
一个简单的解决方案是EXCLUDE
他们在看你的代码,看起来你无论如何都不需要它。
我建议在实例化unknown
参数时将其作为EXCLUDE
传递。
from marshmallow import EXCLUDE
schema = AppSchema(unknown=EXCLUDE)
更多信息可以在这里找到-https://marshmallow.readthedocs.io/en/stable/quickstart.html#handling-未知字段