Ajv: Another JSON Schema Validator
Ajv json驗證器晦毙,出來驗證還需要生產(chǎn)規(guī)定的json
就像適配器妈嘹,usb一樣
Using version 6
JSON Schema draft-07 is published.
JSON Schema draft 規(guī)范已經(jīng)到了第07了
Ajv version 6.0.0 that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes).
如果是使用6的話
Please note: To use Ajv with draft-06 schemas you need to explicitly 明確地 add the meta-schema to the validator instance:
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
如果是使用4的話
To use Ajv with draft-04 schemas in addition to
此外 explicitly 明確地 adding meta-schema you also need to use option schemaId:
你需要這樣子
var ajv = new Ajv({schemaId: 'id'});
// If you want to use both draft-04 and draft-06/07 schemas:
// var ajv = new Ajv({schemaId: 'auto'});
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
Contents 內(nèi)容
Performance 性能
Frequently Asked Questions
經(jīng)常問的問題Using in browser
在瀏覽器中使用Command line interface
命令行界面-
Validation 驗證
- Keywords
- Annotation keywords
- Formats
-
Combining schemas with $ref
將模式與$ ref結(jié)合起來 -
$data reference
$數(shù)據(jù)引用
-
Modifying data during validation 在驗證期間修改數(shù)據(jù)
-
API ===>API
Performance 性能
Ajv generates code using doT templates to turn JSON Schemas into super-fast 超級快 validation functions that are 高效 efficient for v8 optimization.
Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks基準:
- json-schema-benchmark - 50% faster than the second place
- jsck benchmark - 20-190% faster
- z-schema benchmark
- themis benchmark
Features
Ajv implements 器物 full JSON Schema draft-06/07 and draft-04 standards:
all validation keywords 關(guān)鍵字(see JSON Schema validation keywords)
full support of remote refs 遠程 (remote schemas have to be added with
addSchema
or compiled to be available)support of circular圓 references between schemas
correct string lengths for strings with unicode pairs (can be turned off)
formats defined by JSON Schema draft-07 standard and custom formats (can be turned off)
validates schemas against meta-schema 根據(jù)元模式驗證模式
supports browsers and Node.js 0.10-8.x
asynchronous loading of referenced schemas during compilation
"All errors" validation mode with option allErrors
error messages with parameters describing error reasons to allow creating custom error messages
i18n error messages support with ajv-i18n package
filtering data from additional properties
assigning defaults to missing properties and items
將缺省值分配給缺少的屬性和項目coercing data to the types specified in
type
keywordsdraft-06/07 keywords
const
,contains
,propertyNames
andif/then/else
draft-06 boolean schemas (
true
/false
as a schema to always pass/fail).keywords
switch
,patternRequired
,formatMaximum
/formatMinimum
andformatExclusiveMaximum
/formatExclusiveMinimum
from JSON Schema extension proposals with ajv-keywords package$data reference to use values from the validated data as values for the schema keywords
asynchronous validation of custom formats and keywords
Currently Ajv is the only validator that passes all the tests from JSON Schema Test Suite (according to json-schema-benchmark, apart from the test that requires that 1.0
is not an integer that is impossible to satisfy in JavaScript).
Install
npm install ajv
Getting started
Try it in the Node.js REPL: https://tonicdev.com/npm/ajv
The fastest validation call:
var Ajv = require('ajv');
var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
var validate = ajv.compile(schema);
var valid = validate(data);
if (!valid) console.log(validate.errors);
See API and Options for more details.
Ajv compiles 編譯 schemas to functions and caches 高速緩存 them in all cases (using schema serialized with fast-json-stable-stringifyor a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again.
The best performance is achieved when using compiled functions returned by compile
or getSchema
methods (there is no additional function call).
Please note: every time a validation function or ajv.validate
are called errors
property is overwritten. You need to copy errors
array reference to another variable if you want to use it later (e.g., in the callback). See Validation errors
驗證關(guān)鍵字
Ajv集成來自JSON Schema標準草案07的所有驗證關(guān)鍵字:
- 類型艰赞,品種匀油;模范;樣式
- for numbers - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf
- for strings - maxLength, minLength, pattern, format
- for arrays - maxItems, minItems, uniqueItems, items, additionalItems, contains
- for objects - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, propertyNames
- for all types - enum, const
- compound keywords - not, oneOf, anyOf, allOf, if/then/else
注釋關(guān)鍵字
JSON模式規(guī)范定義了描述模式本身的幾個注釋關(guān)鍵字成福,但不執(zhí)行任何驗證芳肌。
-
title
anddescription
: 有關(guān)由該模式表示的數(shù)據(jù)的信息 -
$comment
(NEW in draft-07): 給開發(fā)者的信息灵再。使用選項$ comment Ajv記錄或?qū)⒆⑨屪址畟鬟f給用戶提供的函數(shù)肋层。請參閱選項。 See Options. -
default
: 數(shù)據(jù)實例的默認值翎迁,請參閱分配默認值栋猖。 -
examples
(NEW in draft-07): 一組數(shù)據(jù)實例。 Ajv不檢查這些實例對模式的有效性鸳兽。 -
readOnly
andwriteOnly
(NEW in draft-07): 將數(shù)據(jù)實例標記為只讀或只寫與數(shù)據(jù)源(數(shù)據(jù)庫掂铐,api等)相關(guān)的實例。 -
contentMediaType
: RFC 2046, e.g., "image/png".
Formats
使用“format”關(guān)鍵字支持以下格式的字符串驗證:
- date: 根據(jù)RFC3339進行全日制揍异。
- time: time with optional time-zone.
-
date-time: date-time from the same source (time-zone is mandatory).
date
,time
anddate-time
validate ranges infull
mode and only regexp infast
mode (see options). - uri: full URI.
- uri-reference: URI reference, including full and relative URIs.
- uri-template: URI template according to RFC6570
- url: URL record.
- email: email address.
- hostname: host name according to RFC1034.
- ipv4: IP address v4.
- ipv6: IP address v6.
- regex: tests whether a string is a valid regular expression by passing it to RegExp constructor.
- uuid: Universally Unique IDentifier according to RFC4122.
- json-pointer: JSON-pointer according to RFC6901.
- relative-json-pointer: relative JSON-pointer according to this draft.
將schemas 與$ ref結(jié)合起來
您可以在多個模式文件之間構(gòu)建驗證邏輯全陨,并使用$ ref關(guān)鍵字相互引用模式
var schema = {
"$id": "http://example.com/schemas/schema.json",
"type": "object",
"properties": {
"foo": { "$ref": "defs.json#/definitions/int" },
"bar": { "$ref": "defs.json#/definitions/str" }
}
};
//defs.json
var defsSchema = {
"$id": "http://example.com/schemas/defs.json",
"definitions": {
"int": { "type": "integer" },
"str": { "type": "string" }
}
};
現(xiàn)在編譯您的模式,您可以將所有模式傳遞給Ajv實例:
var ajv = new Ajv({schemas: [schema, defsSchema]});
var validate = ajv.getSchema('http://example.com/schemas/schema.json');
請注意:
$ ref被解析為使用模式$ id作為基本URI的uri-reference(請參閱示例)衷掷。
引用可以遞歸(和相互遞歸)來實現(xiàn)不同數(shù)據(jù)結(jié)構(gòu)(如鏈表辱姨,樹,圖等)的模式戚嗅。
您不必在用作模式$ id的URI處托管模式文件雨涛。這些URI僅用于標識模式,根據(jù)JSON模式規(guī)范驗證器不應(yīng)該期望能夠從這些URI下載模式懦胞。 模式文件在文件系統(tǒng)中的實際位置未使用替久。
模式文件在文件系統(tǒng)中的實際位置未使用
您可以將模式的標識符作為addSchema方法的第二個參數(shù)或作為模式中的屬性名稱選項傳遞。這個標識符可以用來代替(或除了)schema $ id躏尉。
您不能擁有用于多個模式的相同的$ id(或模式標識符) - 將拋出異常蚯根。
您可以使用compileAsync方法實現(xiàn)引用架構(gòu)的動態(tài)解析。通過這種方式胀糜,您可以將架構(gòu)存儲在任何系統(tǒng)(文件颅拦,Web,數(shù)據(jù)庫等)中教藻,并在不明確添加到Ajv實例的情況下引用它們距帅。請參閱異步模式編譯。
定義自定義關(guān)鍵字
使用自定義關(guān)鍵字的優(yōu)點是:
允許創(chuàng)建無法使用JSON模式表達的驗證場景
簡化你的模式
有助于將更多的驗證邏輯帶入您的模式
使您的架構(gòu)更具表現(xiàn)力括堤,減少冗長并更接近您的應(yīng)用程序域
您可以使用addKeyword方法定義自定義關(guān)鍵字碌秸。關(guān)鍵字在ajv實例級別定義 - 新實例不會有以前定義的關(guān)鍵字。
Ajv允許定義關(guān)鍵字:
validation function
compilation function
macro function
inline compilation function that should return code (as string) that will be inlined in the currently compiled schema.
ajv.addKeyword('range', {
type: 'number',
compile: function (sch, parentSchema) {
var min = sch[0];
var max = sch[1];
return parentSchema.exclusiveRange === true
? function (data) { return data > min && data < max; }
: function (data) { return data >= min && data <= max; }
}
});
var schema = { "range": [2, 4], "exclusiveRange": true };
var validate = ajv.compile(schema);
console.log(validate(2.01)); // true
console.log(validate(3.99)); // true
console.log(validate(2)); // false
console.log(validate(4)); // false