2018-06-25-看了那么多的文檔 我覺得json schma就這個好ajv

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

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

驗證關(guān)鍵字

Ajv集成來自JSON Schema標準草案07的所有驗證關(guān)鍵字:

注釋關(guān)鍵字

JSON模式規(guī)范定義了描述模式本身的幾個注釋關(guān)鍵字成福,但不執(zhí)行任何驗證芳肌。

  • title and description: 有關(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 and writeOnly (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 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結(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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末痊臭,一起剝皮案震驚了整個濱河市哮肚,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌广匙,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,104評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件恼策,死亡現(xiàn)場離奇詭異鸦致,居然都是意外死亡潮剪,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評論 3 399
  • 文/潘曉璐 我一進店門分唾,熙熙樓的掌柜王于貴愁眉苦臉地迎上來抗碰,“玉大人,你說我怎么就攤上這事绽乔』∮” “怎么了?”我有些...
    開封第一講書人閱讀 168,697評論 0 360
  • 文/不壞的土叔 我叫張陵折砸,是天一觀的道長看疗。 經(jīng)常有香客問我,道長睦授,這世上最難降的妖魔是什么两芳? 我笑而不...
    開封第一講書人閱讀 59,836評論 1 298
  • 正文 為了忘掉前任,我火速辦了婚禮去枷,結(jié)果婚禮上怖辆,老公的妹妹穿的比我還像新娘。我一直安慰自己删顶,他們只是感情好竖螃,可當(dāng)我...
    茶點故事閱讀 68,851評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著逗余,像睡著了一般特咆。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上猎荠,一...
    開封第一講書人閱讀 52,441評論 1 310
  • 那天坚弱,我揣著相機與錄音,去河邊找鬼关摇。 笑死荒叶,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的输虱。 我是一名探鬼主播些楣,決...
    沈念sama閱讀 40,992評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼宪睹!你這毒婦竟也來了愁茁?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,899評論 0 276
  • 序言:老撾萬榮一對情侶失蹤亭病,失蹤者是張志新(化名)和其女友劉穎鹅很,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體罪帖,經(jīng)...
    沈念sama閱讀 46,457評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡促煮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,529評論 3 341
  • 正文 我和宋清朗相戀三年邮屁,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片菠齿。...
    茶點故事閱讀 40,664評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡佑吝,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出绳匀,到底是詐尸還是另有隱情芋忿,我是刑警寧澤,帶...
    沈念sama閱讀 36,346評論 5 350
  • 正文 年R本政府宣布疾棵,位于F島的核電站戈钢,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏陋桂。R本人自食惡果不足惜逆趣,卻給世界環(huán)境...
    茶點故事閱讀 42,025評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望嗜历。 院中可真熱鬧宣渗,春花似錦、人聲如沸梨州。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽暴匠。三九已至鞍恢,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間每窖,已是汗流浹背帮掉。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留窒典,地道東北人蟆炊。 一個月前我還...
    沈念sama閱讀 49,081評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像瀑志,于是被迫代替她去往敵國和親涩搓。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,675評論 2 359

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理劈猪,服務(wù)發(fā)現(xiàn)昧甘,斷路器,智...
    卡卡羅2017閱讀 134,704評論 18 139
  • 十六個月過的是那么平淡战得。沒有醉酒充边,沒有大哭。 可能作為一個男生還是要面子的常侦。眼淚只能留在心里痛黎。 久而久之予弧,釀成酒刮吧。...
    小純潔alvin閱讀 232評論 0 0
  • 【日精進打卡第74】 【知~學(xué)習(xí)】 《六項精進》1遍 共2遍 累計187遍 《大學(xué)》1遍 共2遍 累計185遍 【...
    黃于峰閱讀 102評論 0 0
  • 偶然的機會湖饱,我們遇見了對方。一再的告訴自己杀捻,就是他/她井厌,認準了。但是很多事情總是事與愿違致讥。 最初仅仆,我們會因為對方的...
    mmlym閱讀 562評論 0 3
  • 集合類:list(特定順序) set(元素不重復(fù)) queue(一端插入,一端移除) map(鍵值對) Colle...
    陌路已始閱讀 209評論 0 1