2018-06-25-看了那么多的文档 我觉得json schma就这个好ajv

Ajv: Another JSON Schema Validator

Ajv json验证器,出来验证还需要生产规定的json
就像适配器,usb一样

Using version 6

JSON Schema draft-07 is published.
JSON Schema draft 规范已经到了第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 内容

  • Performance 性能

  • Features

  • Getting started

  • Frequently Asked Questions
    经常问的问题

  • Using in browser
    在浏览器中使用

  • Command line interface
    命令行界面

  • Validation 验证

    • Keywords
    • Annotation keywords
    • Formats
    • Combining schemas with $ref
      将模式与$ ref结合起来
    • $data reference
      $数据引用
  • NEW: $merge and $patch keywords

    • Defining custom keywords
    • Asynchronous schema compilation
    • Asynchronous validation
  • Modifying data during validation 在验证期间修改数据

    • Filtering data
    • Assigning defaults
    • Coercing data types
  • API ===>API

    • Methods
    • Options
    • Validation errors
  • Plugins

  • Related packages

  • Packages using Ajv

  • Tests, Contributing, History, License


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
2018-06-25-看了那么多的文档 我觉得json schma就这个好ajv_第1张图片
image.png

Features


Ajv implements 器物 full JSON Schema draft-06/07 and draft-04 standards:

  • all validation keywords 关键字(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 根据元模式验证模式

  • 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 keywords

  • custom keywords

  • draft-06/07 keywords const, contains, propertyNames and if/then/else

  • draft-06 boolean schemas (true/false as a schema to always pass/fail).

  • keywords switch, patternRequired, formatMaximum / formatMinimum and formatExclusiveMaximum / 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

验证关键字

Ajv集成来自JSON Schema标准草案07的所有验证关键字:

  • 类型,品种;模范;样式
  • 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

注释关键字

JSON模式规范定义了描述模式本身的几个注释关键字,但不执行任何验证。

  • title and description: 有关由该模式表示的数据的信息
  • $comment (NEW in draft-07): 给开发者的信息。使用选项$ comment Ajv记录或将注释字符串传递给用户提供的函数。请参阅选项。 See Options.
  • default: 数据实例的默认值,请参阅分配默认值。
  • examples (NEW in draft-07): 一组数据实例。 Ajv不检查这些实例对模式的有效性。
  • readOnly and writeOnly (NEW in draft-07): 将数据实例标记为只读或只写与数据源(数据库,api等)相关的实例。
  • contentMediaType: RFC 2046, e.g., "image/png".

Formats


使用“format”关键字支持以下格式的字符串验证:

  • date: 根据RFC3339进行全日制。
  • time: time with optional time-zone.
  • date-time: date-time from the same source (time-zone is mandatory). date, time and date-time validate ranges in fullmode and only regexp in fast 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结合起来


您可以在多个模式文件之间构建验证逻辑,并使用$ ref关键字相互引用模式

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" }
  }
};

现在编译您的模式,您可以将所有模式传递给Ajv实例:

var ajv = new Ajv({schemas: [schema, defsSchema]});
var validate = ajv.getSchema('http://example.com/schemas/schema.json');

请注意:
$ ref被解析为使用模式$ id作为基本URI的uri-reference(请参阅示例)。

引用可以递归(和相互递归)来实现不同数据结构(如链表,树,图等)的模式。
您不必在用作模式$ id的URI处托管模式文件。这些URI仅用于标识模式,根据JSON模式规范验证器不应该期望能够从这些URI下载模式。 模式文件在文件系统中的实际位置未使用。
模式文件在文件系统中的实际位置未使用

您可以将模式的标识符作为addSchema方法的第二个参数或作为模式中的属性名称选项传递。这个标识符可以用来代替(或除了)schema $ id。

您不能拥有用于多个模式的相同的$ id(或模式标识符) - 将抛出异常。

您可以使用compileAsync方法实现引用架构的动态解析。通过这种方式,您可以将架构存储在任何系统(文件,Web,数据库等)中,并在不明确添加到Ajv实例的情况下引用它们。请参阅异步模式编译。

定义自定义关键字


使用自定义关键字的优点是:
允许创建无法使用JSON模式表达的验证场景
简化你的模式
有助于将更多的验证逻辑带入您的模式
使您的架构更具表现力,减少冗长并更接近您的应用程序域

您可以使用addKeyword方法定义自定义关键字。关键字在ajv实例级别定义 - 新实例不会有以前定义的关键字。
Ajv允许定义关键字:
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

你可能感兴趣的:(2018-06-25-看了那么多的文档 我觉得json schma就这个好ajv)