Json 节点验证器
Json validator for node
我想使用一个框架来根据一些标准验证给定的 json,例如:
- 可选字段。
- 必填项。
- 拒绝具有架构中未指定字段的 jsons。
Node 是否有某种框架可以做到这一点?
不知道框架,但 ajv 是一个很好的库
https://github.com/epoberezkin/ajv
有一个 light-weight ts-interface-checker which works nicely with TypeScript and ts-interface-builder,但也可以单独使用。
例如:
const t = require("ts-interface-checker");
const {Square} = t.createCheckers({
Square: t.iface([], {
"size": "number",
"color": t.opt("string"),
})
});
Square.check({size: 1}); // OK
Square.check({size: 1, color: "green"}); // OK
Square.check({color: "green"}); // Fails with "value.size is missing"
Square.check({size: 4, color: 5}); // Fails with "value.color is not a string"
Square.strictCheck({size: 4, spin: 5}); // Fails with "value.spin is extraneuous"
我想使用一个框架来根据一些标准验证给定的 json,例如:
- 可选字段。
- 必填项。
- 拒绝具有架构中未指定字段的 jsons。
Node 是否有某种框架可以做到这一点?
不知道框架,但 ajv 是一个很好的库 https://github.com/epoberezkin/ajv
有一个 light-weight ts-interface-checker which works nicely with TypeScript and ts-interface-builder,但也可以单独使用。
例如:
const t = require("ts-interface-checker");
const {Square} = t.createCheckers({
Square: t.iface([], {
"size": "number",
"color": t.opt("string"),
})
});
Square.check({size: 1}); // OK
Square.check({size: 1, color: "green"}); // OK
Square.check({color: "green"}); // Fails with "value.size is missing"
Square.check({size: 4, color: 5}); // Fails with "value.color is not a string"
Square.strictCheck({size: 4, spin: 5}); // Fails with "value.spin is extraneuous"