python棉花糖:验证嵌套请求JSON的任何解决方法?

时间:2020-05-07 15:46:59

标签: python json validation marshmallow

我想使用marshmallow验证嵌套的请求JSON,我几乎遵循其文档来验证我的请求JSON数据。经过几次尝试,我认为使用棉花糖来验证复杂的JSON数据是正确的方法。但是,我从棉花糖收到一个验证错误,如下所示:

更新后的错误消息

> PS C:\Users\jyson\immunomatch_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:\Users\jyson\AppData\Local\Programs\Python\Python37\lib\site-packages\marshmallow\schema.py",
> line 723, in load  
>     data, many=many, partial=partial, unknown=unknown, postprocess=True   File
> "C:\Users\jyson\AppData\Local\Programs\Python\Python37\lib\site-packages\marshmallow\schema.py",
> line 904, in _do_load
>     raise exc marshmallow.exceptions.ValidationError: {'_schema': ['Invalid input type.']}

更新

在出现位置参数错误之前,因为我隐式定义了def __init__(self, age, gender, features)之类的功能,而不是在def init (自身,年龄,性别,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的正确方法是什么?为什么我遇到未知字段错误?任何可能的想法摆脱上面的错误?谢谢

0 个答案:

没有答案