验证JSON Schema时出现「data should be object」错误如何解决
问题根因
你定义的JSON Schema指定了根数据类型为object,但接口实际返回的内容不符合这个类型要求,因此触发校验失败。
Validate json Schema | AssertionError: expected data to satisfy schema but found following errors: data should be object
排查&解决步骤
- 先确认接口实际返回的结构
在测试脚本最顶部添加如下代码,打印返回内容和类型,在Postman控制台查看输出:
console.log("接口返回内容:", pm.response.json()); console.log("返回数据类型:", typeof pm.response.json());
- 根据实际返回结构调整校验规则
- 如果接口返回的是包裹对象的数组(示例:
[{"name":"xxx","isbn":"xxx"}]),将Schema根类型改为array,新增items字段指定数组元素的校验规则,参考代码:
const schema = { "$schema": "http://json-schema.org/draft-07/schema", "type": "array", "items": { "type": "object", "required": ["name", "isbn", "aisle", "author"], "properties": { "name": {"type": "string"}, "isbn": {"type": "string"}, "aisle": {"type": "string"}, "author": {"type": "string"} }, "additionalProperties": true } };
- 如果接口返回的是字符串、数值等非对象类型,根据实际类型修改Schema根节点的
type取值即可。 - 如果接口返回非JSON格式/空内容,先新增前置校验规则,确认接口本身返回正常再做Schema校验:
// 前置校验 pm.test("响应状态码为200", () => pm.response.to.have.status(200)); pm.test("响应为合法JSON格式", () => pm.response.to.be.json); pm.test("Validate json Schema",function(){ pm.response.to.have.jsonSchema(schema); })
注意事项
你当前Schema里examples字段中使用的{{isbn}}等Postman变量不会参与校验逻辑,不会影响校验结果,无需修改。
内容的提问来源于stack exchange,提问作者Shailesh Waghole
相关产品推荐
相关产品推荐

