【问题标题】:python marshmallow: any workaround to validate nested request JSON?python marshmallow:验证嵌套请求 JSON 的任何解决方法?
【发布时间】:2020-05-07 15:46:59
【问题描述】:

我想使用marshmallow 验证嵌套请求 JSON,我几乎按照它的文档来验证我的请求 JSON 数据。经过几次尝试,我认为使用 marshmallow 验证复杂的 JSON 数据是正确的方法。但是,我从 marshmallow 收到了如下验证错误:

更新的错误信息

> 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 的正确方法是什么?为什么我有未知字段错误?任何可能的想法来摆脱上面的错误?谢谢

【问题讨论】:

    标签: python json validation marshmallow


    【解决方案1】:

    错误清楚地提到了问题

    marshmallow.exceptions.ValidationError: {'OM10': ['Unknown field.'], 'CRP': ['Unknown field.'], 'IL10': ['Unknown field.'], 'PCT4': ['Unknown field.']}
    

    Marshmallow 的 Schema 不理解该字段,因为您尚未将其声明到您的架构中,并且默认情况下,如果 Marshmallow 找到 Unknown Field,则会引发错误

    一个简单的解决方法是EXCLUDE他们查看您的代码,看来您无论如何都不需要它。

    我建议在实例化时将unknown 参数作为EXCLUDE 传递。

    from marshmallow import EXCLUDE
    schema = AppSchema(unknown=EXCLUDE)
    

    更多信息可以在这里找到 - https://marshmallow.readthedocs.io/en/stable/quickstart.html#handling-unknown-fields

    【讨论】:

    • 感谢您的提醒。但是在我尝试了你的输入之后,我遇到了这个错误:TypeError: make_app() got an unexpected keyword argument 'many' ,但我通过添加 **kwargs 解决了这个问题。现在我有了这个:TypeError: __init__() missing 1 required positional argument: 'features' ;有什么进一步的想法吗?我在上面粘贴了新的错误消息
    • 我有一个位置参数,因为我必须明确定义像 PCT4IL10 这样的对象,而不是像 featuers 这样的抽象对象。我怎样才能让它工作?我更新了上面的错误信息。谢谢
    • 这不起作用,因为您在 json 中没有 features。您需要定义与 json 中相同的结构。我建议您更改 AppSchema 并在其中添加 PCT4 `CRP`` 等作为嵌套字段
    • 验证后,如何将 app = schema.load(app_data) 序列化回 json 字符串,如 json.dumps(app) ?我会接受你的解决方案。谢谢
    • 是的,就是这样
    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 2019-11-30
    • 2020-06-06
    • 1970-01-01
    相关资源
    最近更新 更多