JSON Schema
json schema
json schema 是一種基于 json 格式定義 json 數(shù)據(jù)結(jié)構(gòu)的規(guī)范。它被寫(xiě)在 ietf 草案下并于 2011 年到期。json 模式:
- 描述現(xiàn)有數(shù)據(jù)格式。
- 干凈的人類(lèi)和機(jī)器可讀的文檔。
- 完整的結(jié)構(gòu)驗(yàn)證,有利于自動(dòng)化測(cè)試。
- 完整的結(jié)構(gòu)驗(yàn)證,可用于驗(yàn)證客戶端提交的數(shù)據(jù)。
1. json 模式驗(yàn)證庫(kù)
目前有好幾個(gè)驗(yàn)證器可用于不同的編程語(yǔ)言。但是目前最完整和兼容 json 模式的驗(yàn)證器是 jsv。
語(yǔ)言 | 程序庫(kù) |
---|---|
c | wjelement (lgplv3) |
java | json-schema-validator (lgplv3) |
.net | json.net (mit) |
actionscript 3 | frigga (mit) |
haskell | aeson-schema (mit) |
python | jsonschema |
ruby | autoparse (asl 2.0); ruby-jsonschema (mit) |
php | php-json-schema (mit). json-schema (berkeley) |
javascript | orderly (bsd); jsv; json-schema; matic (mit); dojo; persevere (modified bsd or afl 2.0); schema.js. |
2. json 模式示例
下面是一個(gè)基本的 json 模式,其中涵蓋了一個(gè)經(jīng)典的產(chǎn)品目錄說(shuō)明:
{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "product", "description": "a product from acme's catalog", "type": "object", "properties": { "id": { "description": "the unique identifier for a product", "type": "integer" }, "name": { "description": "name of the product", "type": "string" }, "price": { "type": "number", "minimum": 0, "exclusiveminimum": true } }, "required": ["id", "name", "price"] }
我們來(lái)看一下可以用于這一模式中的各種重要關(guān)鍵字:
關(guān)鍵字 | 描述 |
---|---|
$schema | $schema 關(guān)鍵字狀態(tài),表示這個(gè)模式與 v4 規(guī)范草案書(shū)寫(xiě)一致。 |
title | 用它給我們的模式提供了標(biāo)題。 |
description | 關(guān)于模式的描述。 |
type | type 關(guān)鍵字在我們的 json 數(shù)據(jù)上定義了第一個(gè)約束:必須是一個(gè) json 對(duì)象。 |
properties | 定義各種鍵和他們的值類(lèi)型,以及用于 json 文件中的最小值和最大值。 |
required | 存放必要屬性列表。 |
minimum | 給值設(shè)置的約束條件,表示可以接受的最小值。 |
exclusiveminimum | 如果存在 "exclusiveminimum" 并且具有布爾值 true,如果它嚴(yán)格意義上大于 "minimum" 的值則實(shí)例有效。 |
maximum | 給值設(shè)置的約束條件,表示可以接受的最大值。 |
exclusivemaximum | 如果存在 "exclusiveminimum" 并且具有布爾值 true,如果它嚴(yán)格意義上小于 "maximum" 的值則實(shí)例有效。 |
multipleof | 如果通過(guò)這個(gè)關(guān)鍵字的值分割實(shí)例的結(jié)果是一個(gè)數(shù)字則表示緊靠 "multipleof" 的數(shù)字實(shí)例是有效的。 |
maxlength | 字符串實(shí)例字符的最大長(zhǎng)度數(shù)值。 |
minlength | 字符串實(shí)例字符的最小長(zhǎng)度數(shù)值。 |
pattern | 如果正則表達(dá)式匹配實(shí)例成功則字符串實(shí)例被認(rèn)為是有效的。 |
可以在 http://json-schema.org 上檢出可用于定義 json 模式的完整關(guān)鍵字列表。上面的模式可用于測(cè)試下面給出的 json 代碼的有效性:
[ { "id": 2, "name": "an ice sculpture", "price": 12.50, }, { "id": 3, "name": "a blue mouse", "price": 25.50, } ]