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 性能

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基准:

image.png

Features


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

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的所有验证关键字:

注释关键字

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
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,652评论 18 139
  • 十六个月过的是那么平淡。没有醉酒,没有大哭。 可能作为一个男生还是要面子的。眼泪只能留在心里。 久而久之,酿成酒。...
    小纯洁alvin阅读 228评论 0 0
  • 【日精进打卡第74】 【知~学习】 《六项精进》1遍 共2遍 累计187遍 《大学》1遍 共2遍 累计185遍 【...
    黄于峰阅读 100评论 0 0
  • 偶然的机会,我们遇见了对方。一再的告诉自己,就是他/她,认准了。但是很多事情总是事与愿违。 最初,我们会因为对方的...
    mmlym阅读 557评论 0 3
  • 集合类:list(特定顺序) set(元素不重复) queue(一端插入,一端移除) map(键值对) Colle...
    陌路已始阅读 207评论 0 1