Python Flask使用Marshmallow验证嵌套对象数组JSON出现类型无效报错
问题原因及解决方案
1. 先修复Schema的语法错误
你定义的RequestObject类中,field_d字段的代码末尾缺少右括号,会直接导致语法报错,先修正:
# 修正前 field_d = fields.String(required=True, validate=validate.Length(max=10) # 修正后 field_d = fields.String(required=True, validate=validate.Length(max=10))
2. 检查请求头配置
你收到的field_g下的Invalid input type报错,最常见的原因是Postman发送请求时没有设置正确的Content-Type:
- 请在Postman的请求Headers中添加键值对:
Content-Type: application/json - 如果没有该请求头,Flask的
request.get_json()会返回None,将None传入验证方法时,Schema期望field_g为列表类型,自然触发类型错误。你可以先打印request.get_json()的返回值确认是否为None。
3. 修正Payload的类型不匹配问题
你的Payload中存在多处类型和Schema定义不匹配的问题,即使请求头正确也会触发验证失败:
field_e在Schema中定义为Number类型,Payload中传了字符串格式的"100.0",去掉引号改为"field_e": 100.0field_c在Schema中定义为Integer类型,Payload中传了字符串格式的浮点数值"200.0",改为整数格式"field_c": 200
可选优化点
Nested字段的参数可以直接传Schema类,不需要传实例,写法更规范:
# 原写法 field_g = fields.Nested(NestedObj1(), required=True, many=True) # 优化后写法 field_g = fields.Nested(NestedObj1, required=True, many=True)
内容的提问来源于stack exchange,提问作者MrGlode
相关产品推荐
相关产品推荐

