JSON Schema 校验 JSON 数据:让非法数据进不来
当上下游都约定好一份 JSON Schema,任何不符合结构的数据都该在入口被拦下,而不是污染业务逻辑。
用 ajv 校验(Node/浏览器)
import Ajv from "ajv";
const ajv = new Ajv();
const validate = ajv.compile(schema);
const ok = validate(data);
if (!ok) console.log(validate.errors);
先有 Schema
你可以用 工具 从样本一键生成基线 Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"id": { "type": "integer" },
"name": { "type": "string" },
"active": { "type": "boolean" },
"tags": { "type": "array", "items": { "type": "string" } },
"profile": {
"type": "object",
"properties": {
"city": { "type": "string" },
"followers": { "type": "integer" }
},
"required": ["city", "followers"],
"additionalProperties": false
},
"scores": { "type": "array", "items": { "type": "number" } }
},
"required": ["id", "name", "active", "tags", "profile", "scores"],
"additionalProperties": false
}
适合场景
- 接口入参校验
- 配置文件格式检查
- 第三方数据接入前的体检
常见问题
校验库推荐哪个?
ajv 是社区最主流的 JSON Schema 校验库,支持 draft-07,性能也好。
生成的 Schema 能直接给 ajv 用吗?
可以,工具输出即 draft-07,ajv 默认支持。
相关阅读